1. Home
  2. Computing & Technology
  3. C / C++ / C#

C# Tutorial - Learn the Fundamentals of Programming

By David Bolton, About.com

3 of 10

About Example 1

This is a very simple demonstration of the different C# types and how you declare them. It also shows how to time code using the built in C# 2.0 Stopwatch class.

The first eight lines assign values to various integer variables. However this line

float fbad = 89.0; // Won't compile
gives a compile error and should be commented out. The default type for floating point arithmetic is double and the compiler can't implicitly convert a double to a float. Adding an f suffix to the literal tells the compiler it is a float sized number. This line
float fgood2 = (float)89.0;
also compiles but as a general rule, you should ask yourself why you are forcing casts like this. The compiler is ok about the loss of precision, that's what the cast is doing but you need to check it rather than just make changes so it will compile.

Coming from a C and C++ world, I always wrap expressions in brackets even when, as in the assignment to the bool variable atEnd, they are not needed. This evaluates i==45 as true or false and then assigns that value.

The second part of this program times a double loop. I timed this with different types for the i3 variable: int, uint, long, ulong, ushort and short. As expected the int version was the fastest but the unsigned versions were slightly slower than their signed versions which could involve an additional overflow check.

On the next page : Learn about Enumerated Types

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. Example 1 Explained

©2009 About.com, a part of The New York Times Company.

All rights reserved.