Sonny Childs
Sonny Childs

Reputation: 598

Anonymous Type Variable with Explicit Casting

Can you declare an anonymously-typed variable with explicit casting?

For example, you can do this:

var student = new { ID = 1 , name = "Jim" };

But not this:

var student = new { int ID = 1 , string name = "Jim" };

The goal is to have a variable that is:

As for the question of 'Why?', this is more of an informational curiosity of mine. Suppose you wanted ID to be an Int64.

Upvotes: 2

Views: 420

Answers (1)

Jamiec
Jamiec

Reputation: 136164

No, anonymous types determine the data type implicitly.

Suppose you wanted ID to be an Int64.

Then be explicit by casting to the type you require:

var student = new { ID = (long)1 , name = "Jim" };

or by using a suffix

var student = new { ID = 1L , name = "Jim" };

Upvotes: 9

Related Questions