C# is a strongly-typed language. It means we must declare the type of a variable which indicates the kind of values it is going to store such as integer, float, decimal, text, etc.
string stringVar = "Hello World!!"; int intVar = 100; float floatVar = 10.2f; char charVar = 'A'; bool boolVar = true;
C# mainly categorized data types in two types: Value types and Reference types. Value types include simple types (e.g. int, float, bool, and char), enum types, struct types, and Nullable value types. Reference types include class types, interface types, delegate types, and array types.
A data type specifies the size and type of variable values. It is important to use the correct data type for the corresponding variable; to avoid errors, to save time and memory, but it will also make your code more maintainable and readable. The most common data types are:
Data Type | Size | Description |
---|---|---|
int | 4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647 |
long | 8 bytes | Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
float | 4 bytes | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits |
double | 8 bytes | Stores fractional numbers. Sufficient for storing 15 decimal digits |
bool | 1 bit | Stores true or false values |
char | 2 bytes | Stores a single character/letter, surrounded by single quotes |
string | 2 bytes per character | Stores a sequence of characters, surrounded by double quotes |
Numbers
Int
The int data type is 32-bit signed integer. It can store numbers from -2,147,483,648 to 2,147,483,647.
int myNum = 100000; Console.WriteLine(myNum);
Long
The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. This is used when int is not large enough to store the value. Note that you should end the value with an “L”:
long myNum = 15000000000L; Console.WriteLine(myNum);
Long
Floating Point Types
Float
float myNum = 5.75F; Console.WriteLine(myNum);
Double
The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you can end the value with a “D” (although not required):
double myNum = 19.99D; Console.WriteLine(myNum);
Decimal
The decimal data type can store fractional numbers from ±1.0 x 10-28 to ±7.9228 x 1028.
decimal d1 = 123456789123456789123456789.5m; decimal d2 = 1.1234567891345679123456789123m; Console.WriteLine(d1); Console.WriteLine(d2);
String
In C#, a string is a series of characters that is used to represent text. It can be a character, a word or a long passage surrounded with the double quotes “. The following are string literals.
string ch = "S"; string word = "String"; string text = "This is a string."; Console.WriteLine(ch); Console.WriteLine(word);
String and string
There two ways to declare a string variable in C#. Using System.String class and using string keyword. Both are the same and make no difference. Learn string vs String for more info.
string str1 = "Hello"; // uses string keyword String str2 = "Hello"; // uses System.String class
Special Characters
A text in the real world can include any character. In C#, because a string is surrounded with double quotes, it cannot include ” in a string. The following will give a compile-time error.
C# includes escaping character \ (backslash) before these special characters to include in a string.
Use backslash \ before double quotes and some special characters such as \,\n,\r,\t, etc. to include it in a string.
string text = "This is a \"string\" in C#."; string str = "xyzdef\\rabc"; string path = "\\\\mypc\\ shared\\project";
Escape Sequence
Use @ and \ to declare a multi-line string.
string str = @"xyzdef\rabc"; string path = @"\\mypc\shared\project"; string email = @"[email protected]";
String Concatenation
Multiple strings can be concatenated with + operator.
string name = "Mr." + "James " + "Bond" + ", Code: 007"; string firstName = "James"; string lastName = "Bond"; string code = "007"; string agent = "Mr." + firstName + " " + lastName + ", Code: " + code;
C# DateTime
C# includes DateTime struct to work with dates and times.
To work with date and time in C#, create an object of the DateTime struct using the new keyword. The following creates a DateTime object with the default value.
Create DateTime Object
The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight). The maximum value can be December 31, 9999 11:59:59 P.M.
//assigns default value 01/01/0001 00:00:00 DateTime dt1 = new DateTime(); Console.WriteLine(dt1); //assigns year, month, day DateTime dt2 = new DateTime(2015, 12, 31); Console.WriteLine(dt2); //assigns year, month, day, hour, min, seconds DateTime dt3 = new DateTime(2015, 12, 31, 5, 10, 20); Console.WriteLine(dt3); //assigns year, month, day, hour, min, seconds, UTC timezone DateTime dt4 = new DateTime(2015, 12, 31, 5, 10, 20, DateTimeKind.Utc); Console.WriteLine(dt4);
TimeSpan
TimeSpan is a struct that is used to represent time in days, hour, minutes, seconds, and milliseconds.
DateTime dt = new DateTime(2015, 12, 31); TimeSpan ts = new TimeSpan(25,20,55); DateTime newDate = dt.Add(ts); Console.WriteLine(newDate);//1/1/2016 1:20:55 AM
Subtract Dates
Subtraction of two dates results in TimeSpan.
DateTime dt1 = new DateTime(2015, 12, 31); DateTime dt2 = new DateTime(2016, 2, 2); TimeSpan result = dt2.Subtract(dt1);//33.00:00:00
Operators
The DateTime struct overloads +, -, ==, !=, >, <, <=, >= operators to ease out addition, subtraction, and comparison of dates. These make it easy to work with dates.
DateTime dt1 = new DateTime(2015, 12, 20); DateTime dt2 = new DateTime(2016, 12, 31, 5, 10, 20); TimeSpan time = new TimeSpan(10, 5, 25, 50); Console.WriteLine(dt2 + time); // 1/10/2017 10:36:10 AM Console.WriteLine(dt2 - dt1); //377.05:10:20 Console.WriteLine(dt1 == dt2); //False Console.WriteLine(dt1 != dt2); //True Console.WriteLine(dt1 > dt2); //False Console.WriteLine(dt1 < dt2); //True Console.WriteLine(dt1 >= dt2); //False Console.WriteLine(dt1 <= dt2);//True
Convert DateTime to String
The DateTime struct includes the following methods to convert a date and time to string.
Method | Description |
---|---|
ToString | Converts a DateTime value to a string in the specified format of the current culture. |
ToShortDateString | Converts a DateTime value to a short date string (M/d/yyyy pattern) in the current culture. |
ToShortTimeString | Converts a DateTime value to a short time string (h:mm:ss pattern) in the current culture. |
ToLongDateString | Converts a DateTime value to a long date string (dddd, MMMM d, yyyy pattern) in the current culture. |
ToLongTimeString | Converts a DateTime value to a long time string (h:mm:ss tt pattern) in the current culture. |
The following example demonstrates converting DateTime to strings in different formats.
var dt = DateTime.Now; Console.WriteLine("Date String Current Culture: " + dt.ToString("d")); Console.WriteLine("MM/dd/yyyy Format: " + dt.ToString("MM/dd/yyyy")); Console.WriteLine("dddd, dd MMMM yyyy Format: " + dt.ToString("dddd, dd MMMM yyyy")); Console.WriteLine("MM/dd/yyyy h:mm tt Format: " + dt.ToString("MM/dd/yyyy h:mm tt")); Console.WriteLine("MMMM dd Format:" + dt.ToString("MMMM dd")); Console.WriteLine("HH:mm:ss Format: " + dt.ToString("HH:mm:ss")); Console.WriteLine("hh:mm tt Format: " + dt.ToString("hh:mm tt")); Console.WriteLine("Short Date String: " + dt.ToShortDateString()); Console.WriteLine("Long Date String: " + dt.ToLongDateString()); Console.WriteLine("Short Time String: " + dt.ToShortTimeString()); Console.WriteLine("Long Time String: " + dt.ToLongTimeString());
Convert String to DateTime
A valid date and time string can be converted to a DateTime object using Parse(), ParseExact(), TryParse() and TryParseExact() methods.
The Parse() and ParseExact() methods will throw an exception if the specified string is not a valid representation of a date and time. So, it’s recommended to use TryParse() or TryParseExact() method because they return false if a string is not valid.
var str = "5/12/2020"; DateTime dt; var isValidDate = DateTime.TryParse(str, out dt); if(isValidDate) Console.WriteLine(dt); else Console.WriteLine(str + " is not a valid date string");