473,320 Members | 1,699 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

implicit types in C# 3.0, what is the usefulness of them?

The C# 3.0 spec (http://msdn.microsoft.com/vcsharp/future/) contains a
feature called "Implicitly typed local variables".

The type of the variable is determined at compile time based on the
expression to the right of the = sign:

var s = "Hello"; //s is strongly typed to be a string
var i = 25; //i is strongly typed to be an integer

But what I don't understand what advantage it is?

string s = "Hello"; //This is just as easy to type and is easier to
read

What's the story?

Nov 17 '05 #1
59 3129
I guess it would be for the sake of more polymorphic code...? That's my
best guess as if I ever saw someone use that in any normal code I would
smack them... this is of course assuming that I do not hear of any
other valid reason for it.

Nov 17 '05 #2
Chris,

The reason this was introduced was to support LINQ, for permutations on
queries. Basically, when performing a query on an enumerable type, you can
choose what to return. For example, say you have a class with three
properties, FirstName, LastName, and Id. When you perform a query, you can
choose to return a type with just the Id and the LastName. The thing is,
you don't know what that type will be (well, you do, but creating a
compatable type is a pain if you have to do it all the time).

This is where var comes in. It is used along with these anonymous types
to allow implicit typing (after all, what type would you use for the
anonymous type you just created).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Chris Dunaway" <du******@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
The C# 3.0 spec (http://msdn.microsoft.com/vcsharp/future/) contains a
feature called "Implicitly typed local variables".

The type of the variable is determined at compile time based on the
expression to the right of the = sign:

var s = "Hello"; //s is strongly typed to be a string
var i = 25; //i is strongly typed to be an integer

But what I don't understand what advantage it is?

string s = "Hello"; //This is just as easy to type and is easier to
read

What's the story?

Nov 17 '05 #3
gmiley,

See my response, tell me if you think it is valid ;)

I agree, if you know the type beforehand, then yes, you should not use
it, but if you don't know the type (see my response for why you wouldn't
know), you will need this.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"gmiley" <gm****@gmail.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
I guess it would be for the sake of more polymorphic code...? That's my
best guess as if I ever saw someone use that in any normal code I would
smack them... this is of course assuming that I do not hear of any
other valid reason for it.

Nov 17 '05 #4
Yep, i see your point on that, didn't think of it that way. Thanks.

Nov 17 '05 #5
I had a similar question I was asking myself. I understand the need for
anonymous types, but why the "var" key word: See below:
public void Linq1() {
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

var lowNums =
from n in numbers
where n < 5
select n;

Console.WriteLine("Numbers < 5:");
foreach (var x in lowNums) {
Console.WriteLine(x);
}
}

lowNums is Anonymous type, so why not just a type of AType (assuming AType
exists in the FX) instead such as:

AType lowNums =
from n in numbers
where n < 5
select n;
foreach(Atype at in lowNums)
{
Console.WriteLine(at);
}

Is "var" then just sugar? If so, not so sure I like it at first blush.
Maybe there is some other reason.

--
William Stacey [MVP]

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:em**************@TK2MSFTNGP12.phx.gbl...
Chris,

The reason this was introduced was to support LINQ, for permutations on
queries. Basically, when performing a query on an enumerable type, you
can choose what to return. For example, say you have a class with three
properties, FirstName, LastName, and Id. When you perform a query, you
can choose to return a type with just the Id and the LastName. The thing
is, you don't know what that type will be (well, you do, but creating a
compatable type is a pain if you have to do it all the time).

This is where var comes in. It is used along with these anonymous
types to allow implicit typing (after all, what type would you use for the
anonymous type you just created).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Chris Dunaway" <du******@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
The C# 3.0 spec (http://msdn.microsoft.com/vcsharp/future/) contains a
feature called "Implicitly typed local variables".

The type of the variable is determined at compile time based on the
expression to the right of the = sign:

var s = "Hello"; //s is strongly typed to be a string
var i = 25; //i is strongly typed to be an integer

But what I don't understand what advantage it is?

string s = "Hello"; //This is just as easy to type and is easier to
read

What's the story?


Nov 17 '05 #6
Nicholas

Sorry for being dense here, but wouldn't the type returned with just Id and
LastName be that of the original type?

Is this MS basically regressing back to VBScript with the variant type? At
least in Chris's example it looks that way.

Mark

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:em**************@TK2MSFTNGP12.phx.gbl...
Chris,

The reason this was introduced was to support LINQ, for permutations on queries. Basically, when performing a query on an enumerable type, you can choose what to return. For example, say you have a class with three
properties, FirstName, LastName, and Id. When you perform a query, you can choose to return a type with just the Id and the LastName. The thing is,
you don't know what that type will be (well, you do, but creating a
compatable type is a pain if you have to do it all the time).

This is where var comes in. It is used along with these anonymous types to allow implicit typing (after all, what type would you use for the
anonymous type you just created).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Chris Dunaway" <du******@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
The C# 3.0 spec (http://msdn.microsoft.com/vcsharp/future/) contains a
feature called "Implicitly typed local variables".

The type of the variable is determined at compile time based on the
expression to the right of the = sign:

var s = "Hello"; //s is strongly typed to be a string
var i = 25; //i is strongly typed to be an integer

But what I don't understand what advantage it is?

string s = "Hello"; //This is just as easy to type and is easier to
read

What's the story?


Nov 17 '05 #7
William,

The need for var comes when you do this:

Customer[] customers = GetCustomers();
var custs = customers.Where(c => c.City == "Seattle").Select(c => c.Name);

Or, as C# 3.0 would support it:

Customer[] customers = GetCustomers();
var custs = from c in customers where c.City == "Seattle" select c.Name

Since the new type would only have Name as a property, it can't be of
type Customer. It is anonymous, and you need a way of saying "hey, I have
this strongly-typed thingie over here, but I don't know what it's named. I
know what it does, but you take care of the name, and tell me if I do
something with it that's funky".
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"William Stacey [MVP]" <st*****@mvps.org> wrote in message
news:uo**************@tk2msftngp13.phx.gbl...
I had a similar question I was asking myself. I understand the need for
anonymous types, but why the "var" key word: See below:
public void Linq1() {
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

var lowNums =
from n in numbers
where n < 5
select n;

Console.WriteLine("Numbers < 5:");
foreach (var x in lowNums) {
Console.WriteLine(x);
}
}

lowNums is Anonymous type, so why not just a type of AType (assuming AType
exists in the FX) instead such as:

AType lowNums =
from n in numbers
where n < 5
select n;
foreach(Atype at in lowNums)
{
Console.WriteLine(at);
}

Is "var" then just sugar? If so, not so sure I like it at first blush.
Maybe there is some other reason.

--
William Stacey [MVP]

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote
in message news:em**************@TK2MSFTNGP12.phx.gbl...
Chris,

The reason this was introduced was to support LINQ, for permutations
on queries. Basically, when performing a query on an enumerable type,
you can choose what to return. For example, say you have a class with
three properties, FirstName, LastName, and Id. When you perform a query,
you can choose to return a type with just the Id and the LastName. The
thing is, you don't know what that type will be (well, you do, but
creating a compatable type is a pain if you have to do it all the time).

This is where var comes in. It is used along with these anonymous
types to allow implicit typing (after all, what type would you use for
the anonymous type you just created).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Chris Dunaway" <du******@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
The C# 3.0 spec (http://msdn.microsoft.com/vcsharp/future/) contains a
feature called "Implicitly typed local variables".

The type of the variable is determined at compile time based on the
expression to the right of the = sign:

var s = "Hello"; //s is strongly typed to be a string
var i = 25; //i is strongly typed to be an integer

But what I don't understand what advantage it is?

string s = "Hello"; //This is just as easy to type and is easier to
read

What's the story?



Nov 17 '05 #8
Mark,

No, they are not. The compiler is actually creating a new type with
just the Id and Name property. VB Script would interpret the calls to a
property and get them off the original type. This is a new type that is
being returned (and local to the method).

In Chris's example, yes, those types are string, int, etc, etc.
However, that's really not what the var keyword is meant to support. It's
meant to support the LINQ in C# (which can return just subsets of properties
on a type).

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Mark White" <ma*******@yahoo.com> wrote in message
news:e7**************@TK2MSFTNGP12.phx.gbl...
Nicholas

Sorry for being dense here, but wouldn't the type returned with just Id
and
LastName be that of the original type?

Is this MS basically regressing back to VBScript with the variant type?
At
least in Chris's example it looks that way.

Mark

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote
in
message news:em**************@TK2MSFTNGP12.phx.gbl...
Chris,

The reason this was introduced was to support LINQ, for permutations

on
queries. Basically, when performing a query on an enumerable type, you

can
choose what to return. For example, say you have a class with three
properties, FirstName, LastName, and Id. When you perform a query, you

can
choose to return a type with just the Id and the LastName. The thing is,
you don't know what that type will be (well, you do, but creating a
compatable type is a pain if you have to do it all the time).

This is where var comes in. It is used along with these anonymous

types
to allow implicit typing (after all, what type would you use for the
anonymous type you just created).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Chris Dunaway" <du******@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
> The C# 3.0 spec (http://msdn.microsoft.com/vcsharp/future/) contains a
> feature called "Implicitly typed local variables".
>
> The type of the variable is determined at compile time based on the
> expression to the right of the = sign:
>
> var s = "Hello"; //s is strongly typed to be a string
> var i = 25; //i is strongly typed to be an integer
>
> But what I don't understand what advantage it is?
>
> string s = "Hello"; //This is just as easy to type and is easier to
> read
>
> What's the story?
>



Nov 17 '05 #9
I don't think that this is meant to be used as an everyday type, I
still stand by my smacking of people using 'var' when unnecessary.

I can see its application though, as I said, in polymorphism.

public abstract class AClass
{
var UnknownReturnMethod();
public int SomeIntegerMethod()
{
// code
return 0; //or an int variable
}
}

public class myClass : AClass
{
var UnknownReturnMethod()
{
return something;
}
public string KnownReturnMethod()
{
return (string)UnknownReturnMethod();
}

}

Nov 17 '05 #10
gmiley,

That won't compile. The var keyword is only valid in property and
method implementations (that's why they are called implicitly typed local
variables, the focus being on local).
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"gmiley" <gm****@gmail.com> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
I don't think that this is meant to be used as an everyday type, I
still stand by my smacking of people using 'var' when unnecessary.

I can see its application though, as I said, in polymorphism.

public abstract class AClass
{
var UnknownReturnMethod();
public int SomeIntegerMethod()
{
// code
return 0; //or an int variable
}
}

public class myClass : AClass
{
var UnknownReturnMethod()
{
return something;
}
public string KnownReturnMethod()
{
return (string)UnknownReturnMethod();
}

}

Nov 17 '05 #11
> Customer[] customers = GetCustomers();
var custs = customers.Where(c => c.City == "Seattle").Select(c => c.Name);

Or, as C# 3.0 would support it:

Customer[] customers = GetCustomers();
var custs = from c in customers where c.City == "Seattle" select c.Name

Since the new type would only have Name as a property, it can't be of
type Customer. It is anonymous, and you need a way of saying "hey, I have
this strongly-typed thingie over here, but I don't know what it's named.
I know what it does, but you take care of the name, and tell me if I do
something with it that's funky".


Thanks Nicholas. But why not write it like below:

Customer[] customers = GetCustomers();
AType custs = from c in customes where c.City == "Seattle" select c.Name

AType is not some type I created, but the System's Anonomous Type class.
"custs" is still an anonymous type, but it is more direct what we are taking
about and potentially less confusing. There must be a reason they wanted
that "var" keyword.

--
William Stacey [MVP]
Nov 17 '05 #12
Gotcha. That cleared it up for me, thank you.

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:Oq*************@TK2MSFTNGP12.phx.gbl...
Mark,

No, they are not. The compiler is actually creating a new type with
just the Id and Name property. VB Script would interpret the calls to a
property and get them off the original type. This is a new type that is
being returned (and local to the method).

In Chris's example, yes, those types are string, int, etc, etc.
However, that's really not what the var keyword is meant to support. It's
meant to support the LINQ in C# (which can return just subsets of properties on a type).

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Mark White" <ma*******@yahoo.com> wrote in message
news:e7**************@TK2MSFTNGP12.phx.gbl...
Nicholas

Sorry for being dense here, but wouldn't the type returned with just Id
and
LastName be that of the original type?

Is this MS basically regressing back to VBScript with the variant type?
At
least in Chris's example it looks that way.

Mark

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote
in
message news:em**************@TK2MSFTNGP12.phx.gbl...
Chris,

The reason this was introduced was to support LINQ, for permutations
on
queries. Basically, when performing a query on an enumerable type, you

can
choose what to return. For example, say you have a class with three
properties, FirstName, LastName, and Id. When you perform a query, you

can
choose to return a type with just the Id and the LastName. The thing
is, you don't know what that type will be (well, you do, but creating a
compatable type is a pain if you have to do it all the time).

This is where var comes in. It is used along with these anonymous types
to allow implicit typing (after all, what type would you use for the
anonymous type you just created).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Chris Dunaway" <du******@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
> The C# 3.0 spec (http://msdn.microsoft.com/vcsharp/future/) contains

a > feature called "Implicitly typed local variables".
>
> The type of the variable is determined at compile time based on the
> expression to the right of the = sign:
>
> var s = "Hello"; //s is strongly typed to be a string
> var i = 25; //i is strongly typed to be an integer
>
> But what I don't understand what advantage it is?
>
> string s = "Hello"; //This is just as easy to type and is easier to > read
>
> What's the story?
>



Nov 17 '05 #13
I'm pretty sure that won't work. I think everything still have to be
strongly typed, meaning all types have to be known (or inferred) at
compile time, may it be an anonymous type or not.

that's why even in the local scope, you can do

var i = 1.0;

but just

var i;

is illegal since you can't implicitly tell what's the type for i.

gmiley wrote:
I don't think that this is meant to be used as an everyday type, I
still stand by my smacking of people using 'var' when unnecessary.

I can see its application though, as I said, in polymorphism.

public abstract class AClass
{
var UnknownReturnMethod();
public int SomeIntegerMethod()
{
// code
return 0; //or an int variable
}
}

public class myClass : AClass
{
var UnknownReturnMethod()
{
return something;
}
public string KnownReturnMethod()
{
return (string)UnknownReturnMethod();
}

}


Nov 17 '05 #14
William,

This really wouldn't work. With a representation of an anonymous type
like that, you are making it a CLR operation (since you have created a
construct BCL which represents it now), which it isn't. When you compile
with var, it is actually creating a type definition for you, and
substituting that type in compiled assembly.

If you had a .NET representation of an anonymous type, then you are
making it the CLR's responsibility, which would be unecessary.

With the var keyword, they can get the compiler to do all of the work
for them, and not impact the CLR too much.

As a matter of fact, most of the things that are being shown in C# 3.0
are not CLR enhancements, but "compiler trickery". Anders likes to do this,
from what I have seen (anonymous delegates being the first form of it in C#
2.0).

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"William Stacey [MVP]" <st*****@mvps.org> wrote in message
news:uz**************@TK2MSFTNGP14.phx.gbl...
Customer[] customers = GetCustomers();
var custs = customers.Where(c => c.City == "Seattle").Select(c =>
c.Name);

Or, as C# 3.0 would support it:

Customer[] customers = GetCustomers();
var custs = from c in customers where c.City == "Seattle" select c.Name

Since the new type would only have Name as a property, it can't be of
type Customer. It is anonymous, and you need a way of saying "hey, I
have this strongly-typed thingie over here, but I don't know what it's
named. I know what it does, but you take care of the name, and tell me if
I do something with it that's funky".


Thanks Nicholas. But why not write it like below:

Customer[] customers = GetCustomers();
AType custs = from c in customes where c.City == "Seattle" select c.Name

AType is not some type I created, but the System's Anonomous Type class.
"custs" is still an anonymous type, but it is more direct what we are
taking about and potentially less confusing. There must be a reason they
wanted that "var" keyword.

--
William Stacey [MVP]

Nov 17 '05 #15
Sorry, I meant to say projections, not permutations.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:em**************@TK2MSFTNGP12.phx.gbl...
Chris,

The reason this was introduced was to support LINQ, for permutations on
queries. Basically, when performing a query on an enumerable type, you
can choose what to return. For example, say you have a class with three
properties, FirstName, LastName, and Id. When you perform a query, you
can choose to return a type with just the Id and the LastName. The thing
is, you don't know what that type will be (well, you do, but creating a
compatable type is a pain if you have to do it all the time).

This is where var comes in. It is used along with these anonymous
types to allow implicit typing (after all, what type would you use for the
anonymous type you just created).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Chris Dunaway" <du******@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
The C# 3.0 spec (http://msdn.microsoft.com/vcsharp/future/) contains a
feature called "Implicitly typed local variables".

The type of the variable is determined at compile time based on the
expression to the right of the = sign:

var s = "Hello"; //s is strongly typed to be a string
var i = 25; //i is strongly typed to be an integer

But what I don't understand what advantage it is?

string s = "Hello"; //This is just as easy to type and is easier to
read

What's the story?


Nov 17 '05 #16
I see the light. Thanks Nicholas!

--
William Stacey [MVP]

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:ee**************@TK2MSFTNGP09.phx.gbl...
William,

This really wouldn't work. With a representation of an anonymous type
like that, you are making it a CLR operation (since you have created a
construct BCL which represents it now), which it isn't. When you compile
with var, it is actually creating a type definition for you, and
substituting that type in compiled assembly.

If you had a .NET representation of an anonymous type, then you are
making it the CLR's responsibility, which would be unecessary.

With the var keyword, they can get the compiler to do all of the work
for them, and not impact the CLR too much.

As a matter of fact, most of the things that are being shown in C# 3.0
are not CLR enhancements, but "compiler trickery". Anders likes to do
this, from what I have seen (anonymous delegates being the first form of
it in C# 2.0).

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"William Stacey [MVP]" <st*****@mvps.org> wrote in message
news:uz**************@TK2MSFTNGP14.phx.gbl...
Customer[] customers = GetCustomers();
var custs = customers.Where(c => c.City == "Seattle").Select(c =>
c.Name);

Or, as C# 3.0 would support it:

Customer[] customers = GetCustomers();
var custs = from c in customers where c.City == "Seattle" select c.Name

Since the new type would only have Name as a property, it can't be of
type Customer. It is anonymous, and you need a way of saying "hey, I
have this strongly-typed thingie over here, but I don't know what it's
named. I know what it does, but you take care of the name, and tell me
if I do something with it that's funky".


Thanks Nicholas. But why not write it like below:

Customer[] customers = GetCustomers();
AType custs = from c in customes where c.City == "Seattle" select c.Name

AType is not some type I created, but the System's Anonomous Type class.
"custs" is still an anonymous type, but it is more direct what we are
taking about and potentially less confusing. There must be a reason they
wanted that "var" keyword.

--
William Stacey [MVP]


Nov 17 '05 #17


Chris Dunaway wrote:
The C# 3.0 spec (http://msdn.microsoft.com/vcsharp/future/) contains a
feature called "Implicitly typed local variables".
Nice!
var s = "Hello"; //s is strongly typed to be a string
var i = 25; //i is strongly typed to be an integer

But what I don't understand what advantage it is?


I've been wishing for that for quite a while, I have never understood
why modern languages need to be spoon-fed type-declarations. The
compiler must to type-inference on expressions anyway.

There really is no point in declaring static types of local variables,
except if the programmer wish to constrain available operations or make
a note of what type a variable is.

Declaring the type of local storage is really an inherited trait, back
from C, and C got it because compilers weren't that advanced back then
and C programs needed to calculate how much the stack-pointer should move.

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #18
"Chris Dunaway" <du******@gmail.com> writes:
The C# 3.0 spec (http://msdn.microsoft.com/vcsharp/future/) contains a
feature called "Implicitly typed local variables".

The type of the variable is determined at compile time based on the
expression to the right of the = sign:

var s = "Hello"; //s is strongly typed to be a string
var i = 25; //i is strongly typed to be an integer

But what I don't understand what advantage it is?

string s = "Hello"; //This is just as easy to type and is easier to
read

What's the story?


One of the open files in my editor contains this code:

IDictionary<int, IDictionary<String, int>> newtrans =
new HashDictionary<int, IDictionary<String, int>>();
foreach (KeyValuePair<Set<int>, IDictionary<String, Set<int>>> entry in trans)
{
Set<int> k = entry.Key;
IDictionary<String, int> newktrans = new
HashDictionary<String, int>();
foreach (KeyValuePair<String, Set<int>> tr in entry.Value)
newktrans.Add(tr.Key, renamer[tr.Value]);
newtrans.Add(renamer[k], newktrans);
}

Note the atrocious redundancy of type declarations.

With the new "var" feature, one could write instead:

var newtrans = new HashDictionary<int, IDictionary<String, int>>();
foreach (var entry in trans) {
Set<int> k = entry.Key;
var newktrans = new HashDictionary<String, int>();
foreach (var tr in entry.Value)
newktrans.Add(tr.Key, renamer[tr.Value]);
newtrans.Add(renamer[k], newktrans);
}

Peter
--
Department of Natural Sciences http://www.dina.kvl.dk/~sestoft/
Royal Veterinary and Agricultural University * Tel +45 3528 2334
Thorvaldsensvej 40, DK-1871 Frederiksberg C, Denmark * Fax +45 3528 2350
Nov 17 '05 #19
Helge Jensen <he**********@slog.dk> wrote:
var s = "Hello"; //s is strongly typed to be a string
var i = 25; //i is strongly typed to be an integer

But what I don't understand what advantage it is?
I've been wishing for that for quite a while, I have never understood
why modern languages need to be spoon-fed type-declarations. The
compiler must to type-inference on expressions anyway.


I'm not sure it's so much for the compiler's benefit as for the
reader's. Certainly if I'm reading some code, I want to know the types
of all the variables involved. The fewer potential causes for error,
the better.

I can see the point for anonymous types, but you won't catch me using
them elsewhere.
There really is no point in declaring static types of local variables,
except if the programmer wish to constrain available operations or make
a note of what type a variable is.

Declaring the type of local storage is really an inherited trait, back
from C, and C got it because compilers weren't that advanced back then
and C programs needed to calculate how much the stack-pointer should move.


You need to know the type in order to know what expectations to have.
Suppose I have:

var b = 255;
b++;

What's the value of b now? If b is a byte, it's 0. If b is an int, it's
256. You can easily take the same distinction to ints/longs.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #20
You need to know the type in order to know what expectations to have.
Suppose I have:

var b = 255;
b++;

What's the value of b now? If b is a byte, it's 0. If b is an int, it's
256. You can easily take the same distinction to ints/longs.


I assume the language will have a default value. I'd expect int there since
the literal 255 naked is considered an int by the language, isn't it?

It is a bit messy though, I agree. Constraining var to anonymous types and
situations where the type name is already there might make more sense, ie:

var b = new byte(255);
is legal but

var b = 255;
is not.

My nightmare would be something like

var x = MethodCall();(though I don't know if that is allowed or not)
Nov 17 '05 #21
Daniel O'Connell [C# MVP] <onyxkirx@--NOSPAM--comcast.net> wrote:
You need to know the type in order to know what expectations to have.
Suppose I have:

var b = 255;
b++;

What's the value of b now? If b is a byte, it's 0. If b is an int, it's
256. You can easily take the same distinction to ints/longs.
I assume the language will have a default value. I'd expect int there since
the literal 255 naked is considered an int by the language, isn't it?


Yes. What type (without looking) would you expect 2,147,483,648 to be?

I know what I'd have guessed, and I'd have been wrong. By specifying a
type, I don't have to guess, and neither does the person reading the
code.
It is a bit messy though, I agree. Constraining var to anonymous types and
situations where the type name is already there might make more sense, ie:

var b = new byte(255);
is legal but

var b = 255;
is not.
Yes, possibly.
My nightmare would be something like

var x = MethodCall();(though I don't know if that is allowed or not)


I haven't looked in enough detail to know yet.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #22
I haven't followed this thread in its entirety, so perhaps the following has
already been mentioned.

I think anonymous types were introduced so that types could be statically
defined (implicitly, by the compiler), via projection and/or joining in the
new query language. These types are constructed as C# classes by the
compiler and given names that are not accessible to the programmer. The
various intermediate results of the query can be the objects of further
queries, and a rather complicated type inference system is required to keep
things straight. These intermediate types are anonymous and implicit.
Because they are all constructed by the compiler, you get Intellisense, type
safety, code completion, etc. But it is all implemented at compile time as
if the programmer explicitly defined the classes involved and had access to
the class names. Of course, it must be automatic or the query language would
be too cumbersome to be of any use.
So, I think once the C# query designers saw the need to implement the query
system via anonymous classes, they opened up the facility for use (and
misuse) by the c# programmer, letting her use the type inference system
along with anonymous types to do strange and unanticipated things, outside
of the query language (for which the machinery was originally designed). I
think lambda expressions followed the same evolution: they are built
implicitly by the compiler to make the code for the query language, and that
facility is given to the C# programmer outside the query language as well.

The "LINQ on Channel9" video,
http://msdn.microsoft.com/netframework/future/linq/ is a good introduction
as to how the type inference system, anonymous methods, and lambda
expressions are used by the compiler to implement the query language.

BTW, you should view the video to the end, because the last example of the
query language is the one that best hints at its power. The question
arises: what kind of optimization is done (e.g. sorting of intermediate
results before proceeding, use of hash tables/dictionaries for intermediate
results, etc, etc).
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Helge Jensen <he**********@slog.dk> wrote:
> var s = "Hello"; //s is strongly typed to be a string
> var i = 25; //i is strongly typed to be an integer
>
> But what I don't understand what advantage it is?


I've been wishing for that for quite a while, I have never understood
why modern languages need to be spoon-fed type-declarations. The
compiler must to type-inference on expressions anyway.


I'm not sure it's so much for the compiler's benefit as for the
reader's. Certainly if I'm reading some code, I want to know the types
of all the variables involved. The fewer potential causes for error,
the better.

I can see the point for anonymous types, but you won't catch me using
them elsewhere.
There really is no point in declaring static types of local variables,
except if the programmer wish to constrain available operations or make
a note of what type a variable is.

Declaring the type of local storage is really an inherited trait, back
from C, and C got it because compilers weren't that advanced back then
and C programs needed to calculate how much the stack-pointer should
move.


You need to know the type in order to know what expectations to have.
Suppose I have:

var b = 255;
b++;

What's the value of b now? If b is a byte, it's 0. If b is an int, it's
256. You can easily take the same distinction to ints/longs.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #23

"Chris Dunaway" <du******@gmail.com> schrieb im Newsbeitrag
news:11**********************@g49g2000cwa.googlegr oups.com...
The C# 3.0 spec (http://msdn.microsoft.com/vcsharp/future/) contains a
feature called "Implicitly typed local variables".

The type of the variable is determined at compile time based on the
expression to the right of the = sign:

var s = "Hello"; //s is strongly typed to be a string
var i = 25; //i is strongly typed to be an integer

But what I don't understand what advantage it is?

string s = "Hello"; //This is just as easy to type and is easier to
read

What's the story?


Hi Chris,
i think you cited the less interisting examples.
var s = "Hello";
is not much difference to
string s = "Hello";

But compare
var orders = new Dictionary<int,Order>();
to
Dictionary<int,Order> orders = new Dictionary<int,Order>();

Christof
Nov 17 '05 #24

Jon Skeet [C# MVP] wrote:
I'm not sure it's so much for the compiler's benefit as for the
reader's. Certainly if I'm reading some code, I want to know the types
of all the variables involved. The fewer potential causes for error,
the better.
Dynamicly typed languages get by just fine without even the possibility
of typed locals.
I can see the point for anonymous types, but you won't catch me using
them elsewhere.
I can see how it's essential for anonymous types, and how it may be
usefull in other cases.
You need to know the type in order to know what expectations to have.
Suppose I have:

var b = 255;
b++;

What's the value of b now? If b is a byte, it's 0. If b is an int, it's
256. You can easily take the same distinction to ints/longs.


I agree that the above is not good use of var, a good solution is to not
just use the var construct in the above way.

Here are a few examples of places where I think var could be well-used:

When invoking new (here the type is usually explicitly typed twice, or
an interface-name is used):

MyLongClassName x = new MyLongClassName();
using ( var input = new TextReader(...) ) ...

When simply holding the reference for later passing:

var x = f(....);
y.g(x);
y.h(x);
// x not used anymore

The "var x = 255;" example is special, since very few things generate
doubt about which type is returned:

- byte/integer/long constans
- overloaded method with differing return-types

So it should probably not be used in those cases, but pretty much
everywhere else is OK by me for now (being used to dynamic typed languages).

I may still change an implicit type to an explicit if I find code
unreadable. Experience will show more precisely where it's OK, and where
it's a hazzle.

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #25
> My nightmare would be something like

var x = MethodCall();(though I don't know if that is allowed or not)

I check this and it works:
static void Main(string[] args)
{
var s = Program.getsomething();
Console.WriteLine("s is {0}\nIts type is {1}", s,s.GetType().ToString());
Console.ReadLine();
}
static int getsomething() { return 4; }

output is :
s is 4
Its type is System.Int32

Abubakar.

"Daniel O'Connell [C# MVP]" wrote:
You need to know the type in order to know what expectations to have.
Suppose I have:

var b = 255;
b++;

What's the value of b now? If b is a byte, it's 0. If b is an int, it's
256. You can easily take the same distinction to ints/longs.


I assume the language will have a default value. I'd expect int there since
the literal 255 naked is considered an int by the language, isn't it?

It is a bit messy though, I agree. Constraining var to anonymous types and
situations where the type name is already there might make more sense, ie:

var b = new byte(255);
is legal but

var b = 255;
is not.

My nightmare would be something like

var x = MethodCall();(though I don't know if that is allowed or not)

Nov 17 '05 #26
Exactly, Peter. The var keyword saves a lot of extra typing (or using
declarations) that make code _less_ readable. I can't believe that
nobody's able to see past the silly int/string examples. :-(
--
http://www.kynosarges.de
Nov 17 '05 #27


Christoph Nahr wrote:
Exactly, Peter. The var keyword saves a lot of extra typing (or using
declarations) that make code _less_ readable. I can't believe that
nobody's able to see past the silly int/string examples. :-(


/me looks at own posts...

BTW: I don't think the examples are "silly", they show that there are
limits to where var is a GoodThing(TM)

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #28
check this source code:

public static void tmpproc()
{
var someobject = getunknowtype(2);
Console.WriteLine("value is {0}", someobject);
Console.WriteLine("its type is {0}",
someobject.GetType().ToString());
Console.ReadLine();
}

public static object getunknowtype(int i)
{
if (i == 1)
return 5;
else if (i == 2)
return "hello";
else return -1;
}

This code works and based on the number you pass to getunknowtype, a diff
type and its value is returned.
In the tmpproc above the variable "someobject" cant provide me intellisense?
I dont think there is any way for intellisense to work. Cuz type is just
unknown. If developers start using it for replacing "Dictionary<int,Order>()"
kind of expressions,, it'll lead to confusions in there code. Its right what
Nicolas said in some posts that "var" is best suited for when you are using
LINQ. So better leave it for what its intended rather than start using it all
over our code.

Abubakar.

"Christof Nordiek" wrote:

"Chris Dunaway" <du******@gmail.com> schrieb im Newsbeitrag
news:11**********************@g49g2000cwa.googlegr oups.com...
The C# 3.0 spec (http://msdn.microsoft.com/vcsharp/future/) contains a
feature called "Implicitly typed local variables".

The type of the variable is determined at compile time based on the
expression to the right of the = sign:

var s = "Hello"; //s is strongly typed to be a string
var i = 25; //i is strongly typed to be an integer

But what I don't understand what advantage it is?

string s = "Hello"; //This is just as easy to type and is easier to
read

What's the story?


Hi Chris,
i think you cited the less interisting examples.
var s = "Hello";
is not much difference to
string s = "Hello";

But compare
var orders = new Dictionary<int,Order>();
to
Dictionary<int,Order> orders = new Dictionary<int,Order>();

Christof

Nov 17 '05 #29
Christoph Nahr wrote:
Exactly, Peter. The var keyword saves a lot of extra typing (or using
declarations) that make code less readable. I can't believe that
nobody's able to see past the silly int/string examples. :-(


oh yes we look passed the silly examples. I'll explain why they had to
use var and why it's silly in a strictly typed OO world and why it has
nothing to do with typing.

Say you have a customer and an order table, pretty standard. Order has
a m:1 relation with customer.

Fetching all customers or all orders of a customer is simple, you can
define a customer class or an order class and create instances for each
row you read.

This then could be something like:
CustomerEntity[] customers = myDao.GetCustomers(null);

where GetCustomers simply accepts a filter (here, null) and returns
CustomerEntity instances in an array.

In Sql you can do this:
SELECT C.CustomerID, C.CompanyName, O.OrderID, O.OrderDate
FROM Customers C INNER JOIN Orders O
ON C.CustomerID = O.CustomerID

If you have a customer class and an order class, you're not able to
store this list into a set of object instances. So, instead you have
two options:
1) use an untyped bucket, like a datatable
2) add something to the C# language which creates types on the fly.

In .NET 1.x and 2.x, you'd opt for option 1). In C# 3.0, they have
added option 2) with the 'var' keyword.

The 'var' keyword will create a type for the data returned from a
select, and it's then usable in the code. So if we fetch the list above
with the 4 columns, it would be something like:
var myDynamicList = from customers c, orders o
select c.CustomerID, c.CompanyName,
o.OrderID. o.OrderDate;

(or something, I'm not that familiar with teh new syntax).

Good thing? Well, as you said, let's look passed the silly examples
and look at some real-life scenario.

I have a GUI method which has to display some data, namely a list of
customerid, companyname, orderid and orderdate, very simple. So it
calls the BL tier:
var listToDisplay = myBLObject.GetTheList();

in GetTheList we do:
public var GetTheList()
{
return from customers c, orders o
select c.CustomerID, c.CompanyName,
o.OrderID. o.OrderDate;
}

In the GUI, you now have a list of data, it appears to be typed, as
the compiler knows what's going on, but does the reader of the code?

I don't think so. I mean: is listToDisplay an array, arraylist,
generic collection, 1 object ... what are the properties of the objects
inside the list?

Intellisense will probably show me, but that's not what I have
available when I read the code, I mean, I don't WANT TO fall back on
intellisense to UNDERSTAND code.

Is there an alternative? Sure. Define a simple class with 4 public
fields: CustomerID, CompanyName, OrderID and OrderDate, and create a
list of that. Your BL code then becomes (for example)

List<MyListType> toBind = myBLObject.GetTheList();

hey, all of a sudden we know what the type is in the GUI. Reading the
code, we immediately understand what GetTheList returns: a list of
MyListType objects.

Clarity. This clarity makes it easier to understand code. And when
code is easier to understand, it's less buggy, as the developer easier
spots weirdness in his/her code.

Generics in .NET 2.0 make code more clear, as you don't have to work
with interfaces anymore, you can define strongly typed collections
which are clear. 'var' isn't, it's obscure. And therefore a bad thing.

FB
--
------------------------------------------------------------------------
Get LLBLGen Pro, productive O/R mapping for .NET: http://www.llblgen.com
My .NET blog: http://weblogs.asp.net/fbouma
Microsoft MVP (C#)
------------------------------------------------------------------------
Nov 17 '05 #30
Frans Bouma [C# MVP] wrote:
Christoph Nahr wrote:
Exactly, Peter. The var keyword saves a lot of extra typing (or
using declarations) that make code less readable. I can't believe
that nobody's able to see past the silly int/string examples. :-(


oh yes we look passed the silly examples. I'll explain why they had
to use var and why it's silly in a strictly typed OO world and why it
has nothing to do with typing.


That's 'typing' as in hammering on a keyboard... :D

FB
Nov 17 '05 #31
On Thu, 15 Sep 2005 01:33:07 -0700, "Abubakar"
<Ab******@discussions.microsoft.com> wrote:
If developers start using it for replacing "Dictionary<int,Order>()"
kind of expressions,, it'll lead to confusions in there code.


Not if there is an obviously typed init expression right next to the
var statement! Your example could be written in C# 1.0 and 2.0 using
object instead of var, and it would be just as bad. But that's
because it's generally a bad idea to have a method return either an
int or a string. The var keyword has nothing to do with it.
--
http://www.kynosarges.de
Nov 17 '05 #32
On Thu, 15 Sep 2005 01:41:01 -0700, "Frans Bouma [C# MVP]"
<pe******************@xs4all.nl> wrote:
oh yes we look passed the silly examples. I'll explain why they had to
use var and why it's silly in a strictly typed OO world and why it has
nothing to do with typing.
First off, you're completely ignoring what I think will be the most
frequent usage of the var keyword: inferring the variable type from a
"new" expression. Like I wrote in the other thread:

var x = new MyCompany.MyLongNamespace.MyLongTypeName();

You can simply write "var" instead of having to repeat the namespaces
and type name (or else having to create a "using" alias for the type).
This is pretty much the same as the proposed new use for the "auto"
keyword in C++, or inferred typing in ML.

This is a clear gain, reduces typing (modula IntelliSense in VS,
granted), and makes code just plain more readable. For this purpose
*alone* the var keyword is a great new addition.

Now on to your example where "var" is used to create an unnamed type
on-the-fly, with inferred properties.
The 'var' keyword will create a type for the data returned from a
select, and it's then usable in the code. So if we fetch the list above
with the 4 columns, it would be something like:
var myDynamicList = from customers c, orders o
select c.CustomerID, c.CompanyName,
o.OrderID. o.OrderDate;

(or something, I'm not that familiar with teh new syntax).
Okay, never mind the syntax, let's say this is possible.
public var GetTheList()
Here's the trick: you cannot do this. "var" can only be used in local
variable declarations, not in method declarations.
In the GUI, you now have a list of data, it appears to be typed, as
the compiler knows what's going on, but does the reader of the code?
Yes -- because the selection expression is always visible. Hiding it
away in a method is actually not possible. If you use a method you
must define a proper type, as usual. Nor can you return an object to
hide an anonymous type because the receiver would have no way (short
of reflection) to access its properties, since a cast is not possible.

The inline selection expression clearly shows the properties that the
anonymous type will have: CustomerID, CompanyName, OrderID, OrderDate.
Any renaming is also visible in that expression. No problem.
hey, all of a sudden we know what the type is in the GUI. Reading the
code, we immediately understand what GetTheList returns: a list of
MyListType objects.


That's no different from C# 2.0. Either the GUI gets a distinct type
with known property names or it gets a multipurpose data container.
var and anonymous types are not making any difference here. You can't
use them to decouple subsystems, only for local variables.
--
http://www.kynosarges.de
Nov 17 '05 #33
> var statement! Your example could be written in C# 1.0 and 2.0 using
object instead of var, and it would be just as bad. But that's
no I cant write these kind of confusing statements in earlier versions of
C#. Check this:
void csharpbefore()
{
object obj = new KeyValuePair<int, string>();
//int i = obj.Key; // cant do this can I? Its a compile time error
int i=((KeyValuePair<int, string>)obj).Key;//very clear statement,
everyone knows whats happening, despite the fact that I used an object type
ahead.

}

check this "var" version:
public static void csharpfuture()
{
var obj = new KeyValuePair<int, string>();
// ..... after 60 lines someone rights :
int i = obj.Key; //all valid code and works!
}
but obj.Key will have the developer chasing back in code finding
declarations for obj or in some situations running a compiler in there minds
trying to "infer" what the type will be. This was my point.

Abubakar.

"Christoph Nahr" wrote:
On Thu, 15 Sep 2005 01:33:07 -0700, "Abubakar"
<Ab******@discussions.microsoft.com> wrote:
If developers start using it for replacing "Dictionary<int,Order>()"
kind of expressions,, it'll lead to confusions in there code.


Not if there is an obviously typed init expression right next to the
var statement! Your example could be written in C# 1.0 and 2.0 using
object instead of var, and it would be just as bad. But that's
because it's generally a bad idea to have a method return either an
int or a string. The var keyword has nothing to do with it.
--
http://www.kynosarges.de

Nov 17 '05 #34
ian
http://msdn.microsoft.com/netframewo....aspx?pull=/li
brary/en-us/dndotnet/html/linqprojectovw.asp

watch for linebreaks in the above.

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #35
> int i=((KeyValuePair<int, string>)obj).Key;//very clear statement,
everyone knows whats happening, despite the fact that I used an object type
ahead.

I meant the object type that I used before (up there!!??!!) that type
casting statement. Please pardon my english, its not that good.

Abubakar.

"Abubakar" wrote:
var statement! Your example could be written in C# 1.0 and 2.0 using
object instead of var, and it would be just as bad. But that's


no I cant write these kind of confusing statements in earlier versions of
C#. Check this:
void csharpbefore()
{
object obj = new KeyValuePair<int, string>();
//int i = obj.Key; // cant do this can I? Its a compile time error
int i=((KeyValuePair<int, string>)obj).Key;//very clear statement,
everyone knows whats happening, despite the fact that I used an object type
ahead.

}

check this "var" version:
public static void csharpfuture()
{
var obj = new KeyValuePair<int, string>();
// ..... after 60 lines someone rights :
int i = obj.Key; //all valid code and works!
}
but obj.Key will have the developer chasing back in code finding
declarations for obj or in some situations running a compiler in there minds
trying to "infer" what the type will be. This was my point.

Abubakar.

"Christoph Nahr" wrote:
On Thu, 15 Sep 2005 01:33:07 -0700, "Abubakar"
<Ab******@discussions.microsoft.com> wrote:
If developers start using it for replacing "Dictionary<int,Order>()"
kind of expressions,, it'll lead to confusions in there code.


Not if there is an obviously typed init expression right next to the
var statement! Your example could be written in C# 1.0 and 2.0 using
object instead of var, and it would be just as bad. But that's
because it's generally a bad idea to have a method return either an
int or a string. The var keyword has nothing to do with it.
--
http://www.kynosarges.de

Nov 17 '05 #36
Helge Jensen <he**********@slog.dk> wrote:
I'm not sure it's so much for the compiler's benefit as for the
reader's. Certainly if I'm reading some code, I want to know the types
of all the variables involved. The fewer potential causes for error,
the better.
Dynamicly typed languages get by just fine without even the possibility
of typed locals.


Well, by "get by just fine" - people have bugs due to getting the type
wrong, and the code isn't as easy to follow.

<snip>
So it should probably not be used in those cases, but pretty much
everywhere else is OK by me for now (being used to dynamic typed languages).
I suspect we'll have to agree to differ.
I may still change an implicit type to an explicit if I find code
unreadable. Experience will show more precisely where it's OK, and where
it's a hazzle.


Unfortunately, experience hasn't yet taught people how to write
readable code in general. I suspect people will keep overestimating the
importance of reducing typing time, as they have in the past.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #37

"Abubakar" <Ab******@discussions.microsoft.com> wrote in message
news:37**********************************@microsof t.com...
My nightmare would be something like

var x = MethodCall();(though I don't know if that is allowed or not)


I check this and it works:
static void Main(string[] args)
{
var s = Program.getsomething();
Console.WriteLine("s is {0}\nIts type is {1}",
s,s.GetType().ToString());
Console.ReadLine();
}
static int getsomething() { return 4; }

output is :
s is 4
Its type is System.Int32


Now, that has potential to destroy readability of hte langauge.
Nov 17 '05 #38

check this "var" version:
public static void csharpfuture()
{
var obj = new KeyValuePair<int, string>();
// ..... after 60 lines someone rights :
int i = obj.Key; //all valid code and works!
}
but obj.Key will have the developer chasing back in code finding
declarations for obj or in some situations running a compiler in there
minds
trying to "infer" what the type will be. This was my point.


And the difference in

public static void csharppast()
{
KeyValuePair<int, string> obj = new KeyValuePair<int,string();
//60 lines;
int i = obj.Key;
}

is what, exactly? Since the varaible has a crappy name you stil have to
scroll up or hover over it to figure out its type. Var doesn't create some
mystical new type in this case, it simply allows you to only have to type a
complex type name(KeyValuePair<int,string>) more than one in the
declaration.

Using it when the type isn't evident, such as using a method return or a
literal, sucks, but when used with an object initializer...frankly if you
can't figure out the type without getting confused you aren't good enough to
be using var to start with. It needs some tweaking, certainly, but this
isn't a spot it does.

var x = Q();

now that is something that needs to be eliminated, although I don't know how
to do so without causing some consistency issues within the language.
Nov 17 '05 #39
"Frans Bouma [C# MVP]" wrote:
Intellisense will probably show me, but that's not what I have
available when I read the code, I mean, I don't WANT TO fall back on
intellisense to UNDERSTAND code.


When we get past the logical fallacies such as comparing an object
delcaration to a var declaration this is the main gripe isn't it? We all want
(most of us do) terseness, strong typing and readability. Var clearly handles
terseness and strong typing but readability is left to one of two constructs.

1) Keep your methods small - the age old idiom for readability. If you don't
have to scroll far for your initialization, problem solved. Doesn't however
cover
var x = GetObscureType();

2) Tool support. I'm in favor of this since it for me is a step forward in
computer language design, seeing a programming language as the union of the
written code and the extracted information. "Why do we have to maintain
separate header files" some said before java came along and said "you don't".
Javadoc or minimize all methods gave you the same effect readability-wise.
And the new compilation model solved the other concerns.
Readability criteria are different for different programmers and situations.
A simple mousover (ie intellisense) solves most issues, but if that isn't
enough, any tool should be capable of creating a readonly view (or a
refactoring) operation
view->replace var with type.
Nov 17 '05 #40
It helps the VB.NET programmer make the transition. :-)

The use is not evident in something as simple as:

var i = 1;
var s = "string";

It becomes more useful when dealing with array types, esp. if you are lazy.
:-)

var i = { 1, 2, 3, 4 };
var s = { "1", "2", "3", "4" };

I am not fond of implicit code, so I will have to see a good treatise before
jumping on this bandwagon.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

***************************
Think Outside the Box!
***************************
"Chris Dunaway" wrote:
The C# 3.0 spec (http://msdn.microsoft.com/vcsharp/future/) contains a
feature called "Implicitly typed local variables".

The type of the variable is determined at compile time based on the
expression to the right of the = sign:

var s = "Hello"; //s is strongly typed to be a string
var i = 25; //i is strongly typed to be an integer

But what I don't understand what advantage it is?

string s = "Hello"; //This is just as easy to type and is easier to
read

What's the story?

Nov 17 '05 #41

"Cowboy (Gregory A. Beamer) - MVP" <No************@comcast.netNoSpamM> wrote
in message news:1F**********************************@microsof t.com...
It helps the VB.NET programmer make the transition. :-)

The use is not evident in something as simple as:

var i = 1;
var s = "string";

It becomes more useful when dealing with array types, esp. if you are
lazy.


I prefer it for generics:

Dictionary<int, Dictionary<int, Dictionary<string,int>>> dictionary = new
Dictionary<int, Dictionary<int, Dictionary<string,int>>>()

vs.

var dictionary = new Dictionary<int, Dictionary<int,
Dictionary<string,int>>>();

Now, if var was the way to go, I don't know. It could have some issues with
ref and out parameters, but it does solve those problems and the anonymous
type problem.
Nov 17 '05 #42
Daniel O'Connell [C# MVP] <onyxkirx@--NOSPAM--comcast.net> wrote:
It becomes more useful when dealing with array types, esp. if you are
lazy.
I prefer it for generics:

Dictionary<int, Dictionary<int, Dictionary<string,int>>> dictionary = new
Dictionary<int, Dictionary<int, Dictionary<string,int>>>()

vs.

var dictionary = new Dictionary<int, Dictionary<int,
Dictionary<string,int>>>();


How about using a "using" directive to give it a more meaningful name
though? That would make the code more readable for both the declaration
and the initialisation.
Now, if var was the way to go, I don't know. It could have some issues with
ref and out parameters, but it does solve those problems and the anonymous
type problem.


It certainly solves the anonymous types problem :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #43

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Daniel O'Connell [C# MVP] <onyxkirx@--NOSPAM--comcast.net> wrote:
> It becomes more useful when dealing with array types, esp. if you are
> lazy.


I prefer it for generics:

Dictionary<int, Dictionary<int, Dictionary<string,int>>> dictionary = new
Dictionary<int, Dictionary<int, Dictionary<string,int>>>()

vs.

var dictionary = new Dictionary<int, Dictionary<int,
Dictionary<string,int>>>();


How about using a "using" directive to give it a more meaningful name
though? That would make the code more readable for both the declaration
and the initialisation.


Because then determining the actual type requires reading the using
statement, and I don't consider pretending that you have a third type more
readable, to be honest. var atleast tells me explicitly that the type is not
determined here, a using alias doesn't.
using DictionaryOfDictionaryOfDictionary=new Dictionary<int, Dictionary<int,
Dictionary<string,int>>>;

//100 lines

DictionaryOfDictionaryOfDictionary x;

//can you really tell me that makes things better than

var x = new Dictionary<int, Dictionary<int, Dictionary<string,int>>>();

//which has the literal type right there, not 100 lines above the use of the
alias type?

Nov 17 '05 #44
Daniel O'Connell [C# MVP] <onyxkirx@--NOSPAM--comcast.net> wrote:
How about using a "using" directive to give it a more meaningful name
though? That would make the code more readable for both the declaration
and the initialisation.
Because then determining the actual type requires reading the using
statement, and I don't consider pretending that you have a third type more
readable, to be honest. var atleast tells me explicitly that the type is not
determined here, a using alias doesn't.


What do you mean by "not determined here"? As I understand it, the type
absolutely *is* known at that type.
using DictionaryOfDictionaryOfDictionary=new Dictionary<int, Dictionary<int,
Dictionary<string,int>>>;

//100 lines

DictionaryOfDictionaryOfDictionary x;

//can you really tell me that makes things better than

var x = new Dictionary<int, Dictionary<int, Dictionary<string,int>>>();

//which has the literal type right there, not 100 lines above the use of the
alias type?


No - but then I wouldn't use it in that way. I'd try to give it a
*semantically meaningful* name which makes the precise type either
obvious or irrelevant. For instance, AgeToNameMap is likely to be int
to string, and far more useful than Dictionary<int,string>.

Of course, one difficulty is that I prefer to use the *interface* type
rather than the concrete type wherever possible - and neither solution
solves that problem...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #45
Jon Skeet [C# MVP] <sk***@pobox.com> wrote:
Because then determining the actual type requires reading the using
statement, and I don't consider pretending that you have a third type more
readable, to be honest. var atleast tells me explicitly that the type is not
determined here, a using alias doesn't.
What do you mean by "not determined here"? As I understand it, the type
absolutely *is* known at that type.


Whoops - I mean it's known at that *time*.
No - but then I wouldn't use it in that way. I'd try to give it a
*semantically meaningful* name which makes the precise type either
obvious or irrelevant. For instance, AgeToNameMap is likely to be int
to string, and far more useful than Dictionary<int,string>.

Of course, one difficulty is that I prefer to use the *interface* type
rather than the concrete type wherever possible - and neither solution
solves that problem...


I meant to go into this a bit more, too, because it squashes a *third*
solution which is similar to var but the other way round:

Dictionary<int,Dictionary<int,string>> foo = new(someParameter);

In other words, keep the type with the declaration rather than the
construction - assume any unqualified "new" is calling a constructor of
the class declared as the type of the variable. Doesn't work with
interfaces though...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #46

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Jon Skeet [C# MVP] <sk***@pobox.com> wrote:
> Because then determining the actual type requires reading the using
> statement, and I don't consider pretending that you have a third type
> more
> readable, to be honest. var atleast tells me explicitly that the type
> is not
> determined here, a using alias doesn't.


What do you mean by "not determined here"? As I understand it, the type
absolutely *is* known at that type.


Whoops - I mean it's known at that *time*.


I mean that right at this point in code, from a reader's point of view, the
type is not defined explicitly. Using aliases means that the literal type of
the expression was defined before that point, using var it is defined after.
I don't think aliases solves the problem at all, as the reader is not going
to know the concrete type of the variable at all.
Of course, one difficulty is that I prefer to use the *interface* type
rather than the concrete type wherever possible - and neither solution
solves that problem...


I meant to go into this a bit more, too, because it squashes a *third*
solution which is similar to var but the other way round:

Dictionary<int,Dictionary<int,string>> foo = new(someParameter);

In other words, keep the type with the declaration rather than the
construction - assume any unqualified "new" is calling a constructor of
the class declared as the type of the variable. Doesn't work with
interfaces though...


I can see where you are going here, but interfaces aren't always the answer,
and within method bodies I don't care that much. Dictionary<K,V> vs
IDictionary<K,V> within a single method is pretty irrelevent to me, its when
that reference is passed or returned.

As for using semantically meaningful names...I've never liked that. I'm
interested in the type to know the *type*, not to know the semantic use. The
semantic use is the domain of the variable name, not the type name, IMHO.

var ageToNameMap = ...;

achieves the same thing without a using alias
Nov 17 '05 #47
Daniel O'Connell [C# MVP] <onyxkirx@--NOSPAM--comcast.net> wrote:
In other words, keep the type with the declaration rather than the
construction - assume any unqualified "new" is calling a constructor of
the class declared as the type of the variable. Doesn't work with
interfaces though...
I can see where you are going here, but interfaces aren't always the answer,
and within method bodies I don't care that much. Dictionary<K,V> vs
IDictionary<K,V> within a single method is pretty irrelevent to me, its when
that reference is passed or returned.


While interfaces aren't always the answer, I think it's a good habit to
get into to declare variables with only the information which is really
needed.
As for using semantically meaningful names...I've never liked that. I'm
interested in the type to know the *type*, not to know the semantic use. The
semantic use is the domain of the variable name, not the type name, IMHO.

var ageToNameMap = ...;

achieves the same thing without a using alias


So long as you only need one of them, of course... if you need two
maps, one of which is for students and one for teachers, for instance,
you'd either need to sacrifice some of the intent or have longer names.
If the name of the type gives intent too, there's less need to have it
all in the variable name.

A lot of this is typing as I think, I'll readily admit - it's as much a
gut instinct as anything else. I really just don't like not being able
to see a variable's type immediately from its declaration.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #48
As for using semantically meaningful names...I've never liked that. I'm
interested in the type to know the *type*, not to know the semantic use.
The
semantic use is the domain of the variable name, not the type name, IMHO.

var ageToNameMap = ...;

achieves the same thing without a using alias
So long as you only need one of them, of course... if you need two
maps, one of which is for students and one for teachers, for instance,
you'd either need to sacrifice some of the intent or have longer names.
If the name of the type gives intent too, there's less need to have it
all in the variable name.


Sure, and if you have two uses for Dictionary<K,V> with int, string
parameters, say an ageToNameMap and a idToNameMap, the alias approach can
fail you with lazy coders.

Neither one really fixes the problems, IMHO. A lot of this is typing as I think, I'll readily admit - it's as much a
gut instinct as anything else. I really just don't like not being able
to see a variable's type immediately from its declaration.


Then why use aliases, which does not allow that, period. You have to look up
the type still.
Nov 17 '05 #49
Daniel O'Connell [C# MVP] <onyxkirx@--NOSPAM--comcast.net> wrote:
So long as you only need one of them, of course... if you need two
maps, one of which is for students and one for teachers, for instance,
you'd either need to sacrifice some of the intent or have longer names.
If the name of the type gives intent too, there's less need to have it
all in the variable name.
Sure, and if you have two uses for Dictionary<K,V> with int, string
parameters, say an ageToNameMap and a idToNameMap, the alias approach can
fail you with lazy coders.


True.
Neither one really fixes the problems, IMHO.


No - to be honest, I don't think any approach really does :(
A lot of this is typing as I think, I'll readily admit - it's as much a
gut instinct as anything else. I really just don't like not being able
to see a variable's type immediately from its declaration.


Then why use aliases, which does not allow that, period. You have to look up
the type still.


Only if the type name doesn't give enough information, which I believe
it could. To be honest, I probably wouldn't actually do that - I'd
probably just stick with the long name in both places.

Only time will tell, but I'm going to stay wary of the whole business
for a while...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #50

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Russell Reagan | last post by:
In a newer version of a chess program I am writing, I have created classes that are (more or less) drop in replacements for things that used to be plain old integer or enumerated variables (colors,...
9
by: Simon | last post by:
Hi All, Is it possible to disallow implicit casting for an operand of a function written in C? i.e. void foo(int a) {..} short b; foo(b) // error without explicit cast
25
by: Chad Z. Hower aka Kudzu | last post by:
I have defined some implicit convertors so that I can do: MyStruct x = 4; The implicit convert the 4 into MyStruct. But its essentially a copy constructor and thus if I had: MyStruct x;...
11
by: Aaron Queenan | last post by:
Given the classes: class Class { public static implicit operator int(Class c) { return 0; } } class Holder
36
by: Chad Z. Hower aka Kudzu | last post by:
I have an implicit conversion set up in an assembly from a Stream to something else. In C#, it works. In VB it does not. Does VB support implicit conversions? And if so any idea why it would work...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.