#35 – Declaring Variables
July 22, 2010 5 Comments
In C#, you declare a variable by specifying a type, followed by the name of the new variable. You can also optionally initialize the variable at the time that you declare it.
If you initialize a variable at the time that it is declared, the initializer can be a literal value, an expression, or an array initializer.
float length; int age = 46; string s = "Sean"; Person p; Person q = new Person("Herman", 12); object o = s; int yrsLeft = 100 - age; int[] nums = { 10, 20, 30 }; object[] stuff = { nums, age, q };
how about “var”, where no type is needed but initialization is and the type is taken from the initializer (implicitly typed variables) ?
Yes, keyword var allows type inference at compile time, though variable is still strongly typed. Keyword dynamic allows true dynamic typing, where type is only determined at runtime. I’ll cover both in later posts. But both var and dynamic are additional ways to declare variables.
the comment was made in the sense the var and dynamic should have at least been mentioned (even if covered at a later stage) as they are also part of “Declaring Variables” subject
Pingback: Tweets that mention #35 – Declaring Variables « 2,000 Things You Should Know About C# -- Topsy.com
For built-in types, it’s also a good way to declare them with the default value of that type:
float f = default(float);
int n = default(int);
double d = default(double);
and so on…
the default value of a reference type is: null.