#35 – Declaring Variables

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 };
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

5 Responses to #35 – Declaring Variables

  1. undertakeror says:

    how about “var”, where no type is needed but initialization is and the type is taken from the initializer (implicitly typed variables) ?

    • Sean says:

      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.

  2. undertakeror says:

    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

  3. Pingback: Tweets that mention #35 – Declaring Variables « 2,000 Things You Should Know About C# -- Topsy.com

  4. kai zhou says:

    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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: