C# Fundamental
C# is a mordern object-oriented programming language, which is pronounced as "C Sharp". This way of program designing makes the software designed around data or objects rather than functions and logic.
1. Identifiers
In programming language, the identifiers are always used for identification purpose, for example, in the program, identifiers alwasy define the name of the cmponenets. In C#, an idnetifier can define class name, method name, variable name, etc.
public class A{
static public void Main{
int x;
}
}
We can see 3 indentifiers in this example
- A: Class Name
- Main: Function name
- x: Variable name
Rules for defining indentifier in C#:
There are some rules for defining identifiers in C#. Otherwise, compile-error would be happened.
- The only allowed characters for identifiers are all alphanumeric characters(A-Z,a-z,0-9,"_"). For example, "a@bc" is an invalid identifier in C# program, but "a_bc" is valid.
- identifiers should not start with the numbers(0-9), for example, it cna not be like "0_abc".
- Identifiers should not contain the space.
- Identifiers are not allowed to use as keywords unless they include "@" as a prefix.
- Identifiers allow Unicode Characters.
- Identifiers are case-sensitive.
- Identifiers should not contains more than 512 characters.
- Identifiers do not contain two consecutive underscores.
2. Data Types
Data types specify the type of data that a valid C# variable can hold. Each type of data is predefined as a part of the programming language, furthermore, all constats or variables should be describe with a data type.
Data types in C# can be classified into 3 categories
- Value Data Types
- Reference Data Types
- Pointer Data Types
1. Value Date Types:
Signed or Unsigned Integral Types
Alias | Type | Size | Range |
---|---|---|---|
sbyte | signed integer | 8 | -128 to 127 |
short | signed integer | 16 | -32768 to 32767 |
int | signed integer | 32 | -2E+31 to 2E+31-1 |
long | signed integer | 64 | -2E+63 to 2E+63-1 |
byte | unsigned integer | 8 | 0 to 255 |
ushort | unsigned integer | 16 | 0 to 65535 |
uint | unsigned integer | 0 to 2E+32 | |
ulong | unsigned integer | 64 | 0 to 2E+63 |
Floating Types
Alias | Type | Size | Range |
---|---|---|---|
float | System.Single | 32 | ±1.5E+(-45) to ±3.4E+38 |
double | System.Double | 64 | ±5.0E+(-324) to ±1.7E+308 |
Decimal Types
Alias | Type | Size | Range |
---|---|---|---|
decimal | System.Decimal | 128 | ±1.0E+(-28) to ±7,9228E+28 |
Character Types
Alias | Type | Size | Range |
---|---|---|---|
char | System.Char | 16 | U+0000 to U+ffff |
Exmaple
using System;
namespace ValueTypeTest{
class A{
static void Main(){
char a = 'a';
int i = 66;
short s = 88;
long l = 4567;
uint ui = 76;
ushort us = 99;
ulong ul = 24242422;
double d = 8.3434343434;
float f = 3.32323232f;
decimal dec = 389.5m;
Console.WriteLine("char: "+a);
Console.WriteLine("int: "+i);
Console.WriteLine("short: "+s);
Console.WriteLine("long: "+l);
Console.WriteLine("float: "+f);
Console.WriteLine("double: "+d);
Console.WriteLine("decimal: "+l);
Console.WriteLine("unsigned integer: "+ui);
Console.WriteLine("unsigned short: "+ui);
Console.WriteLine("unsigned long: "+ul);
}
}
}
Output
char: a
int: 66
short: 88
long: 4567
float: 3.323232
double: 8.3434343434
decimal: 389.5
unsigned integer: 76
unsigned short: 99
unsigned long: 24242422
Boolean Types
Alias | Type | Values |
---|---|---|
bool | System.Boolean | True/False |
Example
using System;
namespace BooleanTypes{
class Boolean
{
bool a = true;
if (a == true)
Console.WriteLine("Hi");
}
}
Output
Hi
Enmueration(or enum)
Enumeration is a value data type in C#, it is a set of named interger constants.
Example
using System;
namespace ConsoleApplecation
{
enum month
{
jan,
feb,
mar,
apr,
may
}
class MonthApplecation
{
static void Main(String[] args)
{
Console.WriteLine("The value of jan in month "+"enum is "+(int)month.jan);
Console.WriteLine("The value of feb in month "+"enum is "+(int)month.jan);
Console.WriteLine("The value of mar in month "+"enum is "+(int)month.jan);
Console.WriteLine("The value of apr in month "+"enum is "+(int)month.jan);
Console.WriteLine("The value of may in month "+"enum is "+(int)month.jan);
}
}
}
Output
The value of jan in month enum is 0
The value of feb in month enum is 1
The value of mar in month enum is 2
The value of apr in month enum is 3
The value of may in month enum is 4
2. Reference Data Types:
Reference types do not contain the actual value stored in the variables, but they contain a reference to the variable. In other words, they refer to a memory address.
- String: It contains a sequence od Unicode characters, its type named System.String.
- Object: It is the base class for all the data types in C#. All types inherit directly or indirectly form Object. An Object type can be assigned a value of any other type.
Example
using System;
namespace ReferenceDataTypes{
class ReferenceData
{
string a = "Hello World!"
Console.WriteLine(a);
object obj;
obj=20;
Console.WriteLine(obj);
Console.WriteLine(obj.GetType());
}
}
Output
Hello World!
20
System.Int32
3. Pointer Data Type:
Pointer data type variables store another type of memory address. Pointers in C# have the same function in C/C++.
3. Boxing And Unboxing
Boxing and unboxing are important concept in C#. Basically, Boxing converts a Value Type variable into a Reference Type variable, and Unboxing achieves the vice-versa. The most common scenarios for Boxing and Unboxing is to call a method with a parameter of type Object, which can support any type for general purpose. Boxing is required when you need to pass a value type such as Int32.
Example
using System;
class Boxing{
static public void BoxingTurorial{
int num = 100
Object obj = num;
num = 2020;
System.Console.WriteLine(num);
System.Console.WriteLine(obj);
}
}
Output
2020
100
4. Class and Object
When a class is defined, it is like a blueprint or prototype of the type of data. It does not actually define any data, but it defines what the class means by its name, what an object made of and what performance can be made on this object.
Declaratiob of class
Generally, a class declareations contains only one ketword class, followed by an identifier if the class.
- Modifiers: A class can be public or internal etc. By default modifier of the class is internal.
- Keyword class: A class keyword is used to declare the type class.
- Class Identifier: The variables of type class is peovided. The identifier(or name if the class) should begin with an initial letter which should be capitialized by conention.
- Base class or Super class: The name of the class's parent(super class), if any, proceded by the ":". This is optional.
- Interfaces: A commom-seperated list of interfaces impelemented by the class, if any, preceded by the ":". A class can implement mroe than one interface. This is optional.
- Body: The class body is surrounded by {}(curly braces).
The constructor of a class is a special member function of the class that is excuted when a new object of the class is created. The constructor has exactly same name of the class, and it doest not have any return type.
Example
using System;
class Dog
{
String name;
String breed;
int age;
String color;
public Dog(String name, String breed, int age, String color)
{
this.name=name;
this.breed=breed;
this.age=age;
this.color=color;
}
public String Name()
{
get => name;
set => name = value;
}
public String Breed()
{
get => breed;
set => breed = value;
}
public String Age()
{
get => age;
set => age = value;
}
public String Color()
{
get => color;
set => color = value;
}
public String ToString()
{
return ("Hi, my name is " + this.GetName()
+ ".\n My breed, age, color are" + this.GetBreed() + " ," + this.GetAge() + " ," + this.GetColor());
}
public static void Main(String[] args)
{
Dog a = new Dog("a", "b", 5, "white");
Console.WriteLine(a.ToString());
}
}
Output
Hi, My name is A
My breed, age, color are B, 5, white
Inheritance
Inheritance is one of the most important concept in OOP. It allows programmer to define a class based on another class, in other words, a class can inherit the features from another class.
Important Terminology
- Super Class: The class whose features are inherited is known as super class.(base class/parent class)
- Sub Class: The class inherits the other class is known as sub class(derived class/extend class/child class)
- Reusability: Inheritance supports the concept of "reusability", i.e. when we want to create a class and there is already a class includes some of the code that we want, we can derive our new class in the existing class.
Abstraction
The abstract modifier indicates that the thing being modified has a missing or incomplete implementation.
- An abstract class is declared with the help of abstract keyword.
- In C#, you are not allowed to create objects of the abstract class. Or in other words, you cannot use the abstarct class with new operator.
- Class that contains the abstract keyword with some of its method(not all abstarct method) is known as an abstarct base class.
- Class that contains the abstract keyword with all of its methods is known as pure abstract base class.
- You are not allowed to declare the abstarct methods outside the abstract class.
- You are not allowed to declare an abstract class as Sealed Class
Interface
An interface can define properties, methods, events and indexers as its members. The interface only have the members declaration. The interface itself does not implement any function.
- Interfaces specify what a class must do and not how.
- Interfaces cannot have private members.
- By default all the members of the Interface are public and abstract.
- The interface will always defined with the help of keyword "interface".
- Interface cannot contain fields because they represent a particular implementation of data.
- Multiple inheritance is possible with the help of Interfaces but not with classes.
Difference between abstract class and interface
The abstarct class and interface are similar, they both are used to achieve abstraction where we can declare the abstarct method. But they still have may differences.
Abstarct Class | Interface |
---|---|
It contains declaration and definition part | It only has a declaration part |
It does not support multiple inheritance | It support multiple inheritance |
It contains constructor | It does not contain constructor |
It can contain static members | It cannot contain static members |
Different types of modifiers can be used in it(public/private/protected) | Only public modifier can be used |
A class can only use one abstract class | A class can use multiple interface |
If many implementions are of the same kind and use common behavior, then it is superior to use abstract class | If many implementations only use share methods, then it is superior to use interface |
Abstract class contains methods, fields, constants, etc. | Interface can only contains methods, properties, indexers, events |
It can be fully, partially or not implemented | It should be fully implemented |
5. Exception
An exception is an unwanted or unexpected events which occurs during the program excution. An exception in C# is a response to a special situation, for example, an attempt to devide by 0.
Example
using System;
namespace ErrorHandlingApplecation{
class DivZero{
int result;
DivZero(){
result = 0;
}
public void division(int num1, int num2){
try{
result = num1/num2;
}
catch(DivideByZeroException e){
Console.WriteLine("Exception caught:{0}", e);
}
finally{
Console.WriteLine("Result:{0}", result)
}
}
static void Main(String[] args){
DivZero div = new DivZero;
div.division(25,0);
Console.Readkey();
}
}
}
Output
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ...
Result: 0
Throw Exception
If the exception is derived directly ot indirectly from the System.Exception class, you can use the throw exception statement to throw the exception
Catch(Exception e)
{
...
Throw e
}
6. ADO.NET
ADO.NET provides consist access to data source such as SQL Sever and XML, and data sourse exposed through OLE DB and ODBC. DATA-SHARING consumer applications can use ADO.NET to connnect to these data sources and retrieve, handle, and update data they contain. In other words, ADO.NET is used to communicate between .NET application and data sources.
Components of ADO.NET
Components are designed for data manipulation and faster data access. Connection, Command, DataAdapter, DataSet, DataView are all the components of the ADO.NET that could do the operations on data.
Example
using System;
using System.Data;
using System.Data.SqlClient;
class DbConnection{
static void Main(){
String connectionString=
"Data Source = (local);"
+"Initial Catalog = Northwind;"
+ "Integrated Security = true;";
String queryString =
"SELECT ProductID, UnitPrice, ProductName from dbo.products "
+ "WHERE UnitPrice > @pricePoint "
+ "ORDER BY UnitPrice DESC;";
int paramValue = 5;
using(SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString , connection);
command.Parameters.AddWidthValue("@pricePoint" , paramValue);
try {
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}\t{2}",
reader[0], reader[1], reader[2]);
}
reader.Close();
} catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
7. Generic
Generic allows you to delay writing the data type in the programming class or programming method until it is actually used in the program. In other words, generic allows you write a class or a method with any data type.
Example
using System;
using System.Collections.Generic;
public class MyGenericArray<T>
{
private T[] array;
public MyGenericArray(int size)
{
array = new T[size + 1];
}
public T getItem(int index)
{
return array[index];
}
public void setItem(int index, T value)
{
array[index] = value;
}
}
class Test
{
static void Main()
{
MyGenericArray<int> intArr = new MyGenericArray<int> (5);
}
}
Generic Overview
- Using generic types can maxmize code reuse, protect code safety, and improve the program performance.
- The most common use of generic types is to create collection classes.
- The .NET class library includes some new generic collection classes in the System.Collection.Generic namespace.
- You can create your own generic classes, generic methods, generic interfaces, generic events, generic delegates.
- A generic class can be constained to access methods of a specific data type.
- Information about the types used in generic data types can be obtained at runtime by using reflection.
8. WinForm
WinForm is the abbreviation of Windows Form, which is a Graphical User Interface class bundled in .Net Framework. WinForms can be used in development of Windows Form Applications but not web applications. Windows Form is a UI framework for building windows applications. It provides an efficient way to create desktop application based on visual designer in Visual Studio. Desktop applications can be easily built with features such as drag-and-drop placement of visual control. Using Windows Form, you can develop the graphical apps which can easily deploy and update and work well offline and online.
9. Extension Method
In C#, the extension method concept allows add new methods in exsiting class without modifying the source code and you do not need any special permission from the original type.
Example
First, we create a class named A in Program1, it contains methods M1(), M2(), M3().
using System;
namespace ExtensionMethods{
class A
{
public void M1()
{
Console.WriteLine("Method Name: M1");
}
public void M2()
{
Console.WriteLine("Method Name: M2");
}
public void M3()
{
Console.WriteLine("Method Name: M3");
}
}
}
Then we can create a class named NewMethodClass. It contains 2 methods named M4(), M5(). Now, we add these two methods to A class.
using System;
namespace ExtensionMethods{
static class NewMethodClass{
public static void M4(this A a)
{
Console.WriteLine("Method Name: M4");
}
public static void M5(this A a, String str)
{
Console.WriteLine(str);
}
}
public class Test {
public static void main(String[] args)
{
A a = new A();
a.M1();
a.M2();
a.M3();
a.M4();
a.M4("Method Name: M5");
}
}
}
Output
Method Name: M1
Method Name: M2
Method Name: M3
Method Name: M4
Method Name: M5
10. Events & Delegates
Delegates and events are fundamental to any Windows or Web applications, allowing developer to "subscribe" to partcular actions carried out by user. Events are the notification sent by objects to signal that an action has occured. The class that raise the event is called Publisher, and the class recieves the notification called Subscriber. An event can have multiple subscribers. Typically, publisher raises an event when the action occurs. Subscribers want to be notified when an action occurs, they should register with the event and handle it. In C#, events are encapsulated delegates. It depends on delegates, the delegate defines the signature for the events handler method of the subscribe class.
Example
public delegate void Notify();
public class ProcessBusinessLogic{
public event Notify ProcessCompleted;
public void start Process()
{
Console.WriteLine("Process Started!");
OnProcessCompleted();
}
protected virtual
}
11. Test Framework
The testing is important since it discocers bugs/errors before the dilivery to the client, which can guarantee the quality of the software. It makes the software more reliable and easy to use.
xUnit
The .NET Core platform supports a number of diffrent testing frameworks. However, xUnit has become the most popular testing framework because of its simplicity. The project is supported by .NET fundation.
Example
using System;
using Xunit;
using Validator.Password;
namespace PasswordValidatorTests
{
public class ValidityTest{
[Fact]
public void ValidPassword()
{
//Arrange
var passwordValidator = new PasswordValidator();
const String password = "P@SSWORD";
//ACT
bool isValid = passwordValidator.IsValid(password);
//Assert
Assert.True(isValid, $"The password {password} is not valid");
}
}
}