By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,727 Members | 1,250 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,727 IT Pros & Developers. It's quick & easy.

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

P: n/a
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
Share this Question
Share on Google+
59 Replies


P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
Yep, i see your point on that, didn't think of it that way. Thanks.

Nov 17 '05 #5

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
> 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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a


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

P: n/a
"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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a

"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

P: n/a

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

P: n/a
> 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

P: n/a
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

P: n/a


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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
> 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

P: n/a
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

P: n/a
> 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

P: n/a
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

P: n/a

"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

P: n/a

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

P: n/a
"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

P: n/a
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

P: n/a

"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

P: n/a
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

P: n/a

"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

P: n/a
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

P: n/a
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

P: n/a

"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

P: n/a
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

P: n/a
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

P: n/a
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

59 Replies

This discussion thread is closed

Replies have been disabled for this discussion.