What is C#?

C# Logo

C# (pronounced "see sharp" or "C Sharp") is one of many .NET programming languages. It is object-oriented and allows you to build reusable components for a wide variety of application types. Microsoft introduced C# on June 26th, 2000 and it became a v1.0 product on Feb 13th 2002. 

C# is an evolution of the C and C++ family of languages. However, it borrows features from other programming languages, such as Delphi and Java. If you look at the most basic syntax of both C# and Java, the code looks very similar, but then again, the code looks a lot like C++ too, which is intentional. Developers often ask questions about why C# supports certain features or works in a certain way. The answer is often rooted in it's C++ heritage.

C# has become increasingly popular in recent years, particularly in the world of enterprise software development. It is widely used for developing Windows desktop applications, web applications, and games for various platforms. Some popular examples of applications built with C# include Visual Studio, Unity game engine, and Microsoft Office.


Getting Started with C#: A Beginner's Guide

Are you new to programming and interested in learning C#? Getting started with a new programming language can be daunting, but with a little guidance, it can be a lot easier than you think. This tutorial is designed for beginners who want to learn C# from scratch. 

Visual Studio Logo

1. Install Visual Studio: The first step to getting started with C# is to install a code editor. Visual Studio is a popular code editor used for C# development. You can download the Visual Studio Community Edition for free from Microsoft's website. 

2. Learn the Basics: Once you have installed Visual Studio, it's time to learn the basics of C#. Start with learning about data types, variables, and control structures. Understanding these fundamentals is essential before moving on to more complex topics. 

3. Code Examples: One of the best ways to learn C# is by practicing with code examples. Start with simple programs and gradually move on to more complex programs as you become comfortable with the language. You can find code examples on websites like GitHub or Code Project. 

4. Resources: There are many online resources available to help you learn C#. Microsoft's official website has a comprehensive guide for C# programming. Additionally, there are many blogs and video tutorials available on YouTube and other online platforms. 

5. Join a Community: Joining a community of C# programmers can be beneficial. It's a great way to get help and support as you learn. You can join online forums, social media groups, or even attend local meetups. 

By following these steps, you will be well on your way to becoming a proficient C# programmer. Remember, practice makes perfect, so keep coding and don't be afraid to make mistakes. Good luck!


Understanding C# Keywords: A Comprehensive Guide

C# is a powerful programming language that is widely used for developing various applications, ranging from desktop to web and mobile applications. As a C# programmer, it is important to have a good understanding of the language's keywords. Keywords are reserved words in a programming language that cannot be used as identifiers, such as variable names or method names. 

In C#, there are 79 keywords that are reserved and have a specific meaning in the language. These keywords can be grouped into various categories, such as access modifiers, control flow, data types, operators, and others. 

Here is a list of all the C# keywords: 

Access Modifiers 
  • public 
  • private 
  • protected 
  • internal 
  • protected 
  • internal 

Control Flow 
  • if 
  • else 
  • switch 
  • case 
  • default 
  • while 
  • do 
  • for 
  • foreach 
  • break 
  • continue 
  • goto 
  • return 
  • throw 
  • try 
  • catch 
  • finally 

Data Types 
  • bool 
  • byte 
  • char 
  • decimal 
  • double 
  • float 
  • int 
  • long 
  • sbyte 
  • short 
  • string 
  • uint 
  • ulong 
  • ushort 
  • void 

Modifiers 
  • abstract 
  • async 
  • const 
  • event 
  • extern 
  • new 
  • override 
  • readonly 
  • sealed 
  • static 
  • unsafe 
  • virtual 
  • volatile 

Operators 
  • as 
  • is 
  • sizeof 
  • typeof 

Contextual 
  • add 
  • dynamic 
  • get 
  • global 
  • partial 
  • remove 
  • set 
  • value 
  • var 
  • where 
  • yield 

Each of these keywords has a specific meaning in C# and is used in various parts of the language. For example, access modifiers are used to specify the accessibility of a class, method, or field. Control flow keywords are used to control the flow of execution in a program, such as loops and conditionals. Data type keywords are used to define variables and parameters with a specific data type, such as int or string. 

As a C# programmer, it is important to have a good understanding of these keywords and how they are used in the language. By using the appropriate keywords in the right context, you can write clean, efficient, and maintainable code. 

In this tutorial, we have covered all the C# keywords. By mastering these keywords, you will be well on your way to becoming a proficient C# programmer.


Understanding C# Datatypes: A Comprehensive Guide with Examples

C# is a strongly typed programming language that uses various data types to represent different kinds of data. Understanding C# data types is essential for creating efficient and reliable programs. In this tutorial, we will discuss the different types of data in C# and how to use them effectively. 

C# data types are categorized into two main categories: primitive types and non-primitive types. Primitive types are the most basic types that are built into the C# language, while non-primitive types are types that are created by the programmer. 

Primitive types include bool, byte, char, decimal, double, float, int, long, sbyte, short, uint, ulong, and ushort. 
Non-primitive types include arrays, classes, delegates, enums, interfaces, and structures. 

When using data types in C#, it's important to know the range and limitations of each type. For example, the byte type can only hold values from 0 to 255, while the int type can hold values from -2,147,483,648 to 2,147,483,647. 

The following are the most common datatypes in C# their memory range: 
  • bool: Represents a Boolean value, which can be either true or false. The System.Boolean class is used to represent this datatype. It takes up 1 byte of memory: true or false
  • byte: Represents an unsigned 8-bit integer. The System.Byte class is used to represent this datatype. It takes up 1 byte of memory: 0 to 255. 
  • sbyte: Represents a signed 8-bit integer. The System.SByte class is used to represent this datatype. It takes up 1 byte of memory: –128 to 127. 
  • char: Represents a Unicode character. The System.Char class is used to represent this datatype. It takes up 2 bytes of memory: Unicode characters. 
  • short: Represents a signed 16-bit integer. The System.Int16 class is used to represent this datatype. It takes up 2 bytes of memory: –32768 to 32767. 
  • ushort: Represents an unsigned 16-bit integer. The System.UInt16 class is used to represent this datatype. It takes up 2 bytes of memory: 0 to 65535. 
  • int: Represents a signed 32-bit integer. The System.Int32 class is used to represent this datatype. It takes up 4 bytes of memory: –2147483648 to 2147483647. 
  • uint: Represents an unsigned 32-bit integer. The System.UInt32 class is used to represent this datatype. It takes up 4 bytes of memory: 0 to 4294967295. 
  • long: Represents a signed 64-bit integer. The System.Int64 class is used to represent this datatype. It takes up 8 bytes of memory: –9223372036854775808 to 9223372036854775807. 
  • ulong: Represents an unsigned 64-bit integer. The System.UInt64 class is used to represent this datatype. It takes up 8 bytes of memory: 0 to 18446744073709551615. 
  • float: Represents a single-precision floating-point number. The System.Single class is used to represent this datatype. It takes up 4 bytes of memory: –1.5x10-45 to 3.4 x x1038. 
  • double: Represents a double-precision floating-point number. The System.Double class is used to represent this datatype. It takes up 8 bytes of memory: –5.0x10-324 to 1.7x10308. 
  • decimal: Represents a decimal number with 28 significant digits. The System.Decimal class is used to represent this datatype. It takes up 16 bytes of memory: 1.0x10-28 to 7.9x1028. 

Let's take a look at some examples of how to use these data types in C#:
// Example of primitive types
bool isTrue = true;
byte b = 255;
char c = 'A';
decimal d = 1.23m;
double dbl = 3.14;
float f = 3.14f;
int i = 42;
long l = 123456789L;
sbyte sb = 127;
short s = 32767;
uint ui = 4294967295;
ulong ul = 18446744073709551615;
ushort us = 65535;

// Example of non-primitive types
int[] arr = { 1, 2, 3 };
string str = "Hello World";
object obj = new object();
In this example, we declare variables of different data types and assign them values. We also declare an array of integers, a string, and an object. 

In conclusion, understanding C# data types is crucial for creating effective and efficient programs. By using the appropriate data type for each variable, you can ensure that your program runs smoothly and without errors.


Mastering Explicit Conversion in C#: A Comprehensive Guide

In C#, explicit conversion is the process of converting a value of one data type to another data type, which involves converting the value in a way that might result in a loss of information or precision. This conversion must be explicitly stated in the code, and it requires a cast operator to be used. 

The cast operator in C# is denoted by placing the desired type in parentheses, followed by the value to be converted. For example, if we have a double value that we want to convert to an integer, we would use the following code:
double myDouble = 3.14;
int myInt = (int)myDouble; //Explicit conversion from double to int

In this case, the cast operator is used to convert the double value "myDouble" to an integer value "myInt". Note that this conversion might result in a loss of precision, since the decimal portion of the double value is discarded when it is converted to an integer. 

There are several conversion methods available in C# for performing explicit conversions, including the Convert class, the Parse and TryParse methods, and the ToString method. Here's an example that demonstrates the use of the Convert class:
string myString = "123";
int myInt = Convert.ToInt32(myString);

In this example, the string value "myString" is converted to an integer value "myInt" using the Convert.ToInt32 method. It's important to note that explicit conversion should only be used when necessary, as it can result in a loss of information or precision. 

It's also important to ensure that the conversion is valid before attempting it, using methods such as TryParse to avoid potential runtime errors. 

In summary, explicit conversion is a powerful feature of C# that allows developers to convert values from one data type to another. While it can be useful in certain situations, it should be used with caution and only when necessary.


Understanding Implicit Conversion in C# with Code Examples

In C#, type conversion is the process of converting one data type into another. Implicit conversion is a type of conversion in which the data type is automatically converted by the compiler at compile time. In this tutorial, we will discuss implicit conversion in C# with code examples. 

First, let's understand what is implicit conversion. It is a type of conversion in which the data type is automatically converted by the compiler without any explicit conversion from the user. This happens when the data type of the variable is compatible with the data type of the expression. For example, converting an int to a long or a float to a double. 

The following code example demonstrates implicit conversion:
int numInt = 10;
long numLong = numInt; // implicit conversion from int to long
float numFloat = numInt; // implicit conversion from int to float

In the above code, the variable `numInt` is of type `int` and it is implicitly converted to type `long` and `float` respectively. This conversion is performed by the compiler at compile time without any explicit conversion from the user. 

However, there are certain rules to follow for implicit conversion. For example, the conversion must not result in data loss or overflow. In case of data loss or overflow, explicit conversion must be used.
int numInt = 1000;
byte numByte = numInt; // error: cannot convert int to byte implicitly
byte numByte = (byte)numInt; // explicit conversion from int to byte

In the above code, the variable `numInt` is of type `int` and it cannot be implicitly converted to type `byte` as it can result in data loss. Therefore, explicit conversion is used to convert the value to type `byte`. 

In conclusion, implicit conversion is a useful feature in C# which allows the data types to be automatically converted by the compiler without any explicit conversion from the user. However, it is important to follow the rules of implicit conversion to avoid any data loss or overflow.


Understanding Conversion in C# with Code Examples

C# provides two types of conversion: explicit and implicit. Conversion in C# refers to the process of converting one data type to another. It is a crucial concept in programming because different data types are used to store different kinds of data. Understanding conversion in C# is essential for writing efficient and effective programs. 

Explicit conversion, also known as type casting, is a conversion that must be performed manually. It involves converting a value of one data type to another data type by specifying the desired data type. Explicit conversion is necessary when the target type cannot be implicitly converted from the source type. 
Here is an example:
int num = 1234;
double dblNum = (double)num; //explicit conversion from int to double

Implicit Conversion
Implicit conversion is a conversion that is automatically performed by the C# compiler. It involves converting a value of one data type to another data type without the need for explicit code. Implicit conversion is only possible when the target type can be implicitly converted from the source type. 
Here is an example:
int num = 1234;
double dblNum = num; //implicit conversion from int to double

Type Conversion: 
Type conversion refers to the process of converting one data type to another data type. C# supports various types of type conversion, including conversion between primitive data types, conversion between user-defined types, and conversion between built-in types and user-defined types. 

Converting Data Types: 
Converting data types in C# is essential for working with data effectively. There are various methods for converting data types, including the Parse method, the TryParse method, and the Convert class. The Parse method and TryParse method are used to convert string representations of values to their respective data types. The Convert class can be used to convert values between different data types. 
Here is an example:
string str = "1234";
int num = int.Parse(str); //convert string to int using Parse method

int num2 = Convert.ToInt32("1234"); //convert string to int using Convert class

Understanding conversion in C# is essential for writing efficient and effective programs. By understanding the different types of conversion, you can choose the appropriate method for converting data types in your programs.


Mastering C# Operators: A Comprehensive Guide with Code Examples

Operators are an essential part of any programming language, and C# is no exception. C# provides a wide range of operators that allow you to perform various operations, such as arithmetic, comparison, and logical operations. In this tutorial, we'll explore all the different types of operators in C# and learn how to use them effectively in our programs. 

Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on numeric operands. There are six arithmetic operators in C#: addition (+), subtraction (-), multiplication (*), division (/), modulus (%), and increment/decrement (++/--). Example:
int x = 10, y = 5;
int sum = x + y;
int difference = x - y;
int product = x * y;
int quotient = x / y;
int remainder = x % y;
x++;
y--;
Comparison Operators 
Comparison operators are used to compare the values of two operands. There are six comparison operators in C#: equality (==), inequality (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=). Example:
int x = 10, y = 5;
bool isEqual = x == y;
bool isNotEqual = x != y;
bool isGreaterThan = x > y;
bool isLessThan = x < y;
bool isGreaterOrEqual = x >= y;
bool isLessOrEqual = x <= y;
Logical Operators 
Logical operators are used to perform logical operations on boolean operands. There are three logical operators in C#: AND (&&), OR (||), and NOT (!). Example:
bool a = true, b = false, c = true;
bool andResult = a && b && c;
bool orResult = a || b || c;
bool notResult = !a;
Bitwise Operators 
Bitwise operators are used to perform bit-level operations on operands. There are six bitwise operators in C#: bitwise AND (&), bitwise OR (|), bitwise XOR (^), bitwise complement (~), left shift (<<), and right shift (>>). Example:
int x = 5, y = 3;
int bitwiseAnd = x & y;
int bitwiseOr = x | y;
int bitwiseXor = x ^ y;
int bitwiseComplement = ~x;
int leftShift = x << 1;
int rightShift = x >> 1;
Assignment Operators 
Assignment operators are used to assign a value to a variable. There are several assignment operators in C#: simple assignment (=), addition assignment (+=), subtraction assignment (-=), multiplication assignment (*=), division assignment (/=), modulus assignment (%=), bitwise AND assignment (&=), bitwise OR assignment (|=), bitwise XOR assignment (^=), left shift assignment (<<=), and right shift assignment (>>=). Example:
int x = 10, y = 5;
x = y; // equivalent to x = y;
x += y; // equivalent to x = x + y;
x -= y; // equivalent to x = x - y;
x *= y; // equivalent to x = x * y;
x /= y; // equivalent to x = x / y;
x %= y; // equivalent to x = x % y;
x &= y; // equivalent to x = x & y;
x |= y; // equivalent to x = x | y;
x ^= y; // equivalent to x = x ^ y
x <<= y; // equivalent to x = x << y;
x >>= y; // equivalent to x = x >> y
Conditional Operator 
Conditional Operator is C#: conditional operator or ternary operator (?:). Example:
int x = 10, y = 5;
var result = x > y ? "x is greater than y" : "x is less than y";
Operator Precedence and Associativity
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

Operator Shortcuts 
C# provides some shortcuts for common operations that can be used in assignment expressions. These shortcuts are shown in the following table:
Shortcut OperatorEquivalent Expression
x++ or ++xx = x + 1
x-- or --xx = x - 1
x += yx = x + y
x -= yx = x - y
x *= yx = x * y
x /= yx = x / y
x %= yx = x % y
x <<= yx = x << y
x >>= yx = x >> y
x &= yx = x & y
x |= yx = x | y
x ^= yx = x ^ y

Operators are an essential part of the C# programming language, and understanding them is crucial for writing effective code. In this tutorial, we have covered the various types of operators in C#, their precedence and associativity, and some common shortcuts. By applying this knowledge to your code, you can write more efficient and readable programs. Remember to pay attention to operator precedence and associativity, and you'll be on your way to becoming a C# expert!


Mastering C# Control Statements: A Comprehensive Guide with Code Examples

Control statements are a fundamental concept in programming languages, and C# is no exception. They allow you to control the flow of execution of your code, based on specific conditions. In this tutorial, we'll cover the various control statements available in C#, including if-else statements, switch statements, and loops. We'll also explore the different types of loops available, such as for loops, while loops, and do-while loops. Additionally, we'll discuss the use of keywords like break, continue, and goto. 

If-Else Statements
If-else statements allow you to execute different blocks of code based on a specific condition. 

Here's an example:
int num = 10;
if(num > 0)
{
    Console.WriteLine("The number is positive.");
}
else
{
    Console.WriteLine("The number is negative.");
}
In this example, if the value of num is greater than 0, the first block of code will be executed, and if it's less than or equal to 0, the second block of code will be executed. 

Switch Statements
Switch statements are used to execute different blocks of code based on the value of a variable. 

Here's an example:
int num = 2;
switch(num)
{
    case 1:
        Console.WriteLine("The number is 1");
        break;
    case 2:
        Console.WriteLine("The number is 2");
        break;
    case 3:
        Console.WriteLine("The number is 3");
        break;
    default:
        Console.WriteLine("The number is not between 1 and 3");
        break;
}
In this example, the value of num is checked against three possible values. If it matches one of those values, the corresponding block of code is executed. If it doesn't match any of those values, the default block of code is executed. 

Loops
Loops are used to execute a block of code repeatedly. There are three types of loops in C#: for loops, while loops, and do-while loops. 

For Loops: For loops are used when you know the number of times you want to execute a block of code. 

Here's an example:
for(int i = 0; i < 10; i++)
{
    Console.WriteLine(i);
}
In this example, the block of code inside the for loop is executed 10 times, with the value of i incrementing by 1 each time. 

While Loops: While loops are used when you want to execute a block of code as long as a specific condition is true. 

Here's an example:
int num = 0;
while(num < 5)
{
    Console.WriteLine(num);
    num++;
}
In this example, the block of code inside the while loop is executed as long as num is less than 5. 

Do-While Loops: Do-while loops are similar to while loops, but the block of code is always executed at least once, even if the condition is false. 

Here's an example:
int num = 5;
do
{
    Console.WriteLine(num);
    num--;
} while(num > 0);
In this example, the block of code inside the do-while loop is executed at least once, even though the value of num is already greater than 0 

Jump Statements
These statements allow you to transfer control to another part of your program. There are three types of jump statements in C#: 

break: This statement is used to terminate the nearest enclosing loop or switch statement. 
continue: This statement is used to skip the current iteration of a loop and move to the next iteration. 
goto: This statement is used to transfer control to a labeled statement in your program. 

Here's an example:
for (int c = 0; c < 5; c++)
{
    if (c == 3)
    {
        break;
    }
    Console.WriteLine(c);
}

for (int d = 0; d < 5; d++)
{
    if (d == 3)
    {
        continue;
    }
    Console.WriteLine(d);
}

for (int e = 0; e < 5; e++)
{
    if (e == 3)
    {
        goto mylabel;
    }
    Console.WriteLine(e);
}
mylabel:
Console.WriteLine("Jumped to mylabel");
Now that you understand the different types of control statements in C#, let's dive into some code examples to see how they work in practice. 

Code Example
Let's start with a simple program that uses some of the control statements we've discussed so far.
using System;

namespace ControlStatementsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // If statement
            int x = 10;
            if (x > 5)
            {
                Console.WriteLine("x is greater than 5");
            }

            // If-else statement
            int y = 3;
            if (y > 5)
            {
                Console.WriteLine("y is greater than 5");
            }
            else
            {
                Console.WriteLine("y is less than or equal to 5");
            }

            // Switch statement
            int day = 4;
            switch (day)
            {
                case 1:
                    Console.WriteLine("Monday");
                    break;
                case 2:
                    Console.WriteLine("Tuesday");
                    break;
                case 3:
                    Console.WriteLine("Wednesday");
                    break;
                case 4:
                    Console.WriteLine("Thursday");
                    break;
                case 5:
                    Console.WriteLine("Friday");
                    break;
                default:
                    Console.WriteLine("Weekend");
                    break;
            }

            // While loop
            int i = 0;
            while (i < 5)
            {
                Console.WriteLine(i);
                i++;
            }

            // Do-while loop
            int j = 0;
            do
            {
                Console.WriteLine(j);
                j++;
            } while (j < 5);

            // For loop
            for (int k = 0; k < 5; k++)
            {
                Console.WriteLine(k);
            }

            // Nested loop
            for (int a = 0; a < 3; a++)
            {
                for (int b = 0; b < 3; b++)
                {
                    Console.WriteLine("a: {0}, b: {1}", a, b);
                }
            }

            // Break statement
            for (int c = 0; c < 5; c++)
            {
                if (c == 3)
                {
                    break;
                }
                Console.WriteLine(c);
            }

            // Continue statement
            for (int d = 0; d < 5; d++)
            {
                if (d == 3)
                {
                    continue;
                }
                Console.WriteLine(d);
            }

            // Goto statement
            for (int e = 0; e < 5; e++)
            {
                if (e == 3)
                {
                    goto mylabel;
                }
                Console.WriteLine(e);
            }
            mylabel:
            Console.WriteLine("Jumped to mylabel");
        }
    }
}
In conclusion, control statements are an essential part of C# programming language. They allow you to make decisions based on different conditions and execute code accordingly. In this tutorial, we have covered the basics of control statements including the if-else statement, switch statement, for loop, while loop, do-while loop, and foreach loop. We have also provided code examples to demonstrate how to use these control statements in practical scenarios. By mastering control statements, you can write efficient and flexible code that can perform complex tasks. We hope that this tutorial has provided you with a solid understanding of control statements in C#, and you are now equipped with the knowledge to apply them in your own programs.


Mastering DateTime Format in C#: A Comprehensive Guide of C# DateTime Format

DateTime is an important data type in C# that is used to represent dates and times. It is a versatile class that provides many ways to format dates and times. In this tutorial, we will explore the DateTime format in C#, including custom format, String.Format(), and ToString() methods. This a comprehensive guide about C# DateTime format. 

Understanding DateTime Format 
Before we dive into formatting DateTime in C#, it is important to understand the DateTime format. The DateTime format consists of two parts: date and time. The date part includes the day, month, and year, while the time part includes hours, minutes, seconds, and milliseconds. The DateTime format can be represented in many ways, such as "MM/dd/yyyy HH:mm:ss", "dd-MMM-yyyy h:mm tt", etc. A standard date and time format string uses a single character as the format specifier to define the text representation of a DateTime value. 

Following examples show usage of standard format specifiers in String.Format method and the resulting output.
String.Format("{0:t}", dt); // "4:05 PM" ShortTime
String.Format("{0:d}", dt); // "3/9/2008" ShortDate
String.Format("{0:T}", dt); // "4:05:07 PM" LongTime
String.Format("{0:D}", dt); // "Sunday, March 09, 2008" LongDate
String.Format("{0:f}", dt); // "Sunday, March 09, 2008 4:05 PM" LongDate+ShortTime
String.Format("{0:F}", dt); // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt); // "3/9/2008 4:05 PM" ShortDate+ShortTime
String.Format("{0:G}", dt); // "3/9/2008 4:05:07 PM" ShortDate+LongTime
String.Format("{0:m}", dt); // "March 09" MonthDay
String.Format("{0:y}", dt); // "March, 2008" YearMonth
String.Format("{0:r}", dt); // "Sun, 09 Mar 2008 16:05:07 GMT" RFC1123
String.Format("{0:s}", dt); // "2008-03-09T16:05:07" SortableDateTime
String.Format("{0:u}", dt); // "2008-03-09 16:05:07Z" UniversalSortableDateTime
The format specifiers are: 
  • y (year) 
  • M (month) 
  • d (day) 
  • h (hour 12) 
  • H (hour 24) 
  • m (minute) 
  • s (second) 
  • f (second fraction) 
  • F (second fraction, trailing zeroes are trimmed) 
  • t (P.M or A.M) 
  • z (time zone) 

Custom DateTime Format
C# provides the DateTime.ToString() method that allows us to format DateTime using custom format strings. Custom format strings consist of one or more format specifiers that define how the date and time will be formatted. For example, to format the DateTime as "MM/dd/yyyy HH:mm:ss", we can use the following code. This will output the current date and time in the specified format.
DateTime now = DateTime.Now;
string formattedDateTime = now.ToString("MM/dd/yyyy HH:mm:ss");
Console.WriteLine(formattedDateTime);
Using String.Format() 
Another way to format DateTime in C# is to use the String.Format() method. String.Format() allows us to concatenate strings and format them using placeholders. The placeholders are denoted by curly braces {} and can contain format specifiers. For example, to format the DateTime as "Today is {0:dddd, MMMM d, yyyy}", we can use the following code. This will output the current date in the specified format.
DateTime now = DateTime.Now;
string formattedDateTime = String.Format("Today is {0:dddd, MMMM d, yyyy}", now);
Console.WriteLine(formattedDateTime);
Common DateTime Format Specifiers
C# provides a number of format specifiers that we can use to format DateTime. Some of the commonly used format specifiers are listed below: 
  • d: Short date pattern (e.g. "MM/dd/yyyy") 
  • D: Long date pattern (e.g. "dddd, MMMM dd, yyyy") 
  • t: Short time pattern (e.g. "h:mm tt") 
  • T: Long time pattern (e.g. "h:mm:ss tt") 
  • f: Full date/time pattern (short time) (e.g. "dddd, MMMM dd, yyyy h:mm tt") 
  • F: Full date/time pattern (long time) (e.g. "dddd, MMMM dd, yyyy h:mm:ss tt") 
  • g: General date/time pattern (short time) (e.g. "MM/dd/yyyy h:mm tt") 
  • G: General date/time pattern (long time) (e.g. "MM/dd/yyyy h:mm:ss tt") 
  • M: Month/day pattern (e.g. "MMMM dd") 
  • Y: Year/month pattern (e.g. "MMMM, yyyy") 

Following examples demonstrate how are the format specifiers rewritten to the output:
// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt); // "8 08 008 2008" year
String.Format("{0:M MM MMM MMMM}", dt); // "3 03 Mar March" month
String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}", dt); // "4 04 16 16" hour 12/24
String.Format("{0:m mm}", dt); // "5 05" minute
String.Format("{0:s ss}", dt); // "7 07" second
String.Format("{0:f ff fff ffff}", dt); // "1 12 123 1230" sec.fraction
String.Format("{0:F FF FFF FFFF}", dt); // "1 12 123 123" without zeroes
String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M.
String.Format("{0:z zz zzz}", dt); // "-6 -06 -06:00" time zone
You can use also date separator / (slash) and time sepatator : (colon). These characters will be rewritten to characters defined in the current DateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparator.
// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)
Here are some examples of custom date and time formatting:
// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt); // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt); // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt); // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}", dt); // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"
In this tutorial, we have learned how to format DateTime in C#. We explored custom format strings, String.Format(), and common format specifiers. With this knowledge, you should be able to format DateTime in any way you need. 

Note: It's important to keep in mind the culture of your audience and application when formatting DateTime. The format of the DateTime may change depending on the location of the user, so it's important to test your code with different cultures and formats.


C# Programming Example with Explanation

Program: Hello World 

This program simply outputs the text "Hello World" to the console.

 
using System;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Hello World");
        Console.ReadLine();
    }
}
Explanation: 
  • The using System; line at the beginning of the program is required in order to use the Console class. 
  • The class Program declaration indicates that this is a C# class named Program
  • The static void Main(string[] args) method is the entry point for the program. 
  • The Console.WriteLine("Hello World"); statement outputs the text "Hello World" to the console. 
  • The Console.ReadLine(); statement waits for the user to press a key before closing the console window.