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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

4 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

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers