===================================
Namespace:
1) it is a Collection of names wherein each name is Unique.
2) They form the logical boundary for a Group of classes.
3) Namespace must be specified in Project-Properties.
Assembly:
1) It is an Output Unit.
2) It is a unit of Deployment & a unit of versioning.
3) Assemblies contain MSIL code.
4) Assemblies are Self-Describing. [e.g. metadata,manifest]
5)An assembly is the primary building block of a .NET Framework application.
6) It is a collection of functionality that is built, versioned, and deployed as a single implementation unit (as one or more files).
7) All managed types and resources are marked either as accessible only within their implementation unit, or by code outside that unit.
Difference between NameSpace and Assembly
A .Net Namespace provides the fundamental unit of logical code grouping while an assembly provides a fundamental unit of physical code grouping.
Namespaces is a logical group of related classes that can be used by any other language targeting the Microsoft .Net framework . It is more used for logical organization of your classes. Namespaces are a way of grouping type names and reducing the chance of name collisions.
=================================
c#.net
NET
. NET is a free, open-source developer platform created by Microsoft. It allows developers to build various types of applications, such as web, desktop, mobile, cloud, gaming, IoT, and more. The platform includes a wide range of tools, libraries, and programming languages like C#, F#, and Visual Basic.
Key Components of .NET:
· .NET Runtime: Manages program execution, including memory management, garbage collection, and security.
· .NET Framework: The original version for Windows applications.
· .NET Core: A cross-platform, modular version of .NET for building applications on Windows, macOS, and Linux.
· ASP.NET: A framework for building web applications and services.
· Entity Framework (EF): An Object-Relational Mapping (ORM) tool to work with databases.
· Blazor: A framework for building interactive web UIs using C# instead of JavaScript.
· Advantages of .NET:
· Cross-platform support: With .NET Core and .NET 5+, applications can run on multiple operating systems.
· Performance: Highly optimized for speed and scalability.
· Language versatility: Supports multiple programming languages.
· Tooling and Integration: Seamless integration with Visual Studio and other Microsoft tools.
Ñ C# is pronounced "C-Sharp".
Ñ It is an object-oriented programming language created by Microsoft that runs on the .NET Framework.
Ñ C# has roots from the C family, and the language is close to other popular languages like C++ and Java.
Ñ The first version was released in year 2002. The latest version, C# 8, was released in September 2019.
C# is used for:
§ Mobile applications
§ Desktop applications
§ Web applications
§ Web services
§ Web sites
§ Games
§ Database applications
Why Use C#?
v It is one of the most popular programming languages in the world.
v It is easy to learn and simple to use.
v It has a huge community support.
v C# is an object-oriented language which gives a clear structure to programs and allows code to be reused, lowering development costs.
v As C# is close to C, C++ and Java, it makes it easy for programmers to switch to C# or vice versa.
v C# Variables
1.compiler
2.interpreter
3.assembler
Ñ Father of C#.net- Anders Hejlsberg
Ñ C# is used for: Mobile applications Desktop applications Web applications Web services Web sites Games Database applications
First Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace first
{
internal class Program
{
static void Main(string[] args)
{
Console. WriteLine("Welcome to c#");
}
}
}
Second Program
namespace Second
{
internal class Program
{
static void Main(string[] args)
{
String a = "Hello";
Console. WriteLine(a);
}
}
}
======================================================================
Datatypes
· int - stores integers (whole numbers), without decimals, such as 123 or -123
· double - stores floating point numbers, with decimals, such as 19.99 or -19.99
· char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
· string - stores text, such as "Hello World". String values are surrounded by double quotes
· bool - stores values with two states: true or false
Tokens
Token refers to a fundamental unit of code that the compiler uses to understand the structure and meaning of the source code. Here are some examples of tokens in C#:
1. Keywords: These are reserved words with predefined meanings in the C# language, such as class, if, for, while, int, etc.
2. Identifiers: These are names given to entities in a program, such as variables, functions, classes, etc. Identifiers can include letters, digits, and underscores, but must follow certain naming conventions and cannot be a C# keyword.
3. Literals: These are constant values explicitly specified in the code. For example, 42 is an integer literal, "Hello" is a string literal, true is a Boolean literal, etc.
4. Operators: These are symbols used to perform operations on variables or values, such as +, -, *, /, &&, ||, ==, =, etc.
5. Punctuation Marks: These include symbols like parentheses (), braces {}, square brackets [], semicolons; commas, periods., etc., used for grouping, separating, or terminating code elements.
OPERATORS
The followings are the operators in c#:
1. Arithmetic operators
2. Assignment operators
3. Logical operators
4. Conditional operators
5. Relational operators
6. Increment operator
7. Decrement operators
Arithmetic operators
+ - * / %
using System;
using System. Collections. Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace arithmetic
{
internal class Program
{
static void Main(string[] args)
{
int a = 20;
int b = 10;
Console. WriteLine("SUM=" + (a + b));
Console. WriteLine("difference=" + (a - b));
Console. WriteLine("product=" + (a * b));
Console. WriteLine("division=" + (a / b));
Console. WriteLine("modulus=" + (a % b));
}
}
}
======================================================================
Assignment operators
+= -= *= /= %=
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace assignment operator
{
internal class Program
{
static void Main(string[] args)
{
int a = 20;
a += 3;
Console. WriteLine(a);
a -= 2;
Console. WriteLine(a);
a *= 3;
Console. WriteLine(a);
a /= 4;
Console. WriteLine(a);
a %= 2;
Console. WriteLine(a);
}
}
}
======================================================================
Conditional operators
Ø Syntax: (condition)? True: false;
Console. WriteLine("Enter 2 numbers:");
Int a=Convert.ToInt32(Console.ReadLine());
int b=Convert.ToInt32(Console.ReadLine());
int max = (a > b) ? a : b; Console. WriteLine("big= “+max);
======================================================================
Logical operators
( AND &&, OR || , NOT EQUALTO !=)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace logical operators
{
internal class Program
{
static void Main(string[] args)
{
Console. WriteLine("Enter 4 numbers");
int a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
int c = Convert.ToInt32(Console.ReadLine());
int d = Convert.ToInt32(Console.ReadLine());
if ((a > b) && (a > c) && (a > d))
Console. WriteLine("big= " + a);
else if ((b > a) && (b > c) && (b > d))
Console. WriteLine("big= " + b);
else if (c > d)
Console. WriteLine("big= " + c);
else
Console. WriteLine("big=" + d);
}
}}
======================================================================
Logical OR
Console. WriteLine("Enter a character");
char a = Convert.ToChar(Console.ReadLine());’
if((a=='a' ) || (a=='e') || (a=='i') || (a=='o') ||(a=='u'))
{
Console. WriteLine("Vowels");
}
else { Console. WriteLine("Not a vowel"); }
Notequal
Console. WriteLine("Enter a number");
int a = Convert.ToInt32(Console.ReadLine());
if (a % 2 == 0)
Console. WriteLine("even");
if (a % 2 != 0)
Console. WriteLine("ODD");
======================================================================
Increment/Decrement Operators
Console. WriteLine("Enter a number");
int a = Convert.ToInt32(Console.ReadLine());
a++; //increment
Console. WriteLine(a);
a--; //decrement
Console. WriteLine(a);
======================================================================
Relational operators
> ,<,>=,<=
Console. WriteLine("enter two numbers");
int a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
if (a > b)
Console. WriteLine("big=" + a);
else
Console. WriteLine("big=" + b);
======================================================================
Control Structures
1. If
Syntax:
if(condition)
{
//statements;
}
Console.WriteLine("enter two numbers");
int a = Convert.ToInt32(Console.ReadLine());
if (a > 0)
Console.WriteLine("POSITIVE");
else
Console.WriteLine("NEGATIVE");
}
Console.WriteLine("Enter 2 numbers:");
int a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
if (a > b)
{
Console.WriteLine(a+" is the bigger number");
}
else
{
Console.WriteLine(b+" is the bigger number");
}
}
=======================================================
static void Main(string[] args)
{
Console.WriteLine("Enter 2 numbers:");
int a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter your choice:");
string c = Console.ReadLine();
if (c == "+")
{
Console.WriteLine(a + b);
}
else if (c == "-")
{
Console.WriteLine(a - b);
}
else if (c == "*")
{
Console.WriteLine(a * b);
}
else if(c=="/")
{
Console.WriteLine(a / b);
}
else
{
Console.WriteLine("Invalid");
}
}
static void Main(string[] args)
{
Console.WriteLine("Enter a letter:");
char c = Convert.ToChar(Console.ReadLine());
if ((c == 'a')||(c =='A'))
{
Console.WriteLine(c+ " is Vowel");
}
else if ((c == 'e') || (c == 'E'))
{
Console.WriteLine(c + " is Vowel");
}
else if ((c == 'i') || (c == 'I'))
{
Console.WriteLine(c + " is Vowel");
}
else if ((c == 'o') || (c == 'O'))
{
Console.WriteLine(c + " is Vowel");
}
else if ((c == 'u') || (c == 'U'))
{
Console.WriteLine(c + " is Vowel");
}
else
{
Console.WriteLine(c + " is not a Vowel");
}
============================================================
static void Main(string[] args)
{
Console.WriteLine("Enter a number:");
int c = Convert.ToInt32(Console.ReadLine());
switch (c)
{
case 1:
Console.WriteLine("One");
break;
case 2:
Console.WriteLine("Two");
break;
case 3:
Console.WriteLine("Three");
break;
case 4:
Console.WriteLine("Four");
break;
case 5:
Console.WriteLine("Five");
break;
default:
Console.WriteLine("Invalid");
break;
}
=============================================================
static void Main(string[] args)
{
Console.WriteLine("Enter two number:");
int c = Convert.ToInt32(Console.ReadLine());
int d = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter your choice");
string a = Console.ReadLine();
switch (a)
{
case "+":
Console.WriteLine(c+d);
break;
case "-":
Console.WriteLine(c-d);
break;
case "*":
Console.WriteLine(c*d);
break;
case "/":
Console.WriteLine(c/d);
break;
default:
Console.WriteLine("Invalid");
break;
}
============================================================
Console.WriteLine("Enter a letter");
char a = Convert.ToChar(Console.ReadLine());
switch (a)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
Console.WriteLine("VOWELS");
break;
default:
Console.WriteLine("Not a Vowel");
break;
}
internal class Program
{
static void Main(string[] args)
{
int i = 0;
while (i <= 10)
{
Console.WriteLine(i);
i++;
}
}
}
}
static void Main(string[] args)
{
int i = 10;
while (i >= 0)
{
Console.WriteLine(i);
i--;
}
}
}
}
static void Main(string[] args)
{
int i = 19;
while (i >= 0)
{
Console.WriteLine(i);
i-=2;
}
}
}
}
static void Main(string[] args)
{
int i = 19;
do
{
Console.WriteLine(i);
i -= 2;
}
while (i >= 0);
}
}
}
internal class Program
{
static void Main(string[] args)
{
for (int i = 0; i<=20;i++)
{
Console.WriteLine(i);
}
}
}
}
static void Main(string[] args)
{
for (int i = 0; i<=50;i+=7)
{
Console.WriteLine(i);
}
}
}
}
static void Main(string[] args)
{
for (int i = 1; i<=10;i++)
{
Console.WriteLine(i+"*7="+(i*7) );
}
}
}
}
Console.WriteLine("Enter a number");
int a =Convert.ToInt32(Console.ReadLine());
for (int i = 1; i<=10;i++)
{
Console.WriteLine(i+"*"+a+"="+(i*a) );
}
}
}
}
OR
Console.WriteLine("Enter a number");
int n =Convert.ToInt32(Console.ReadLine());
for (int i = 1; i<=10;i++)
{
//Console.WriteLine(i+"*"+a+"="+(i*a) );
Console.WriteLine("{0}*{1}={2}", i, n, i * n);
}
=========================================================================
static void Main(string[] args)
{
Console.WriteLine("Enter three number");
int n =Convert.ToInt32(Console.ReadLine());
int m = Convert.ToInt32(Console.ReadLine());
int l = Convert.ToInt32(Console.ReadLine());
int a = n * m * l;
Console.WriteLine("{0}*{1}*{2}={3}",n,m,l,a);
}
}
}
static void Main(string[] args)
{
int[] Arrayint = { 10, 44, 22, 15 };
foreach (int m in Arrayint)
{
Console.WriteLine("" + m);
}
}
}
}
static void Main(string[] args)
{
String[] Arrays = { "hello", "what", "welcome", "thankyou" };
foreach (String m in Arrays)
{
Console.WriteLine("" + m);
}
string[] cars = { "Volvo", "BMW", "Ford", "Mazda" ,"maruthi"};
for (int i = 0; i < cars.Length; i++)
{
Console.WriteLine(cars[i]);
}
Console.WriteLine(cars.Length);
}
}
Console.WriteLine("Enter the numbers");
int[] a = new int[5];
for (int i = 0; i < a.Length; i++)
{
a[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The Elements are");
for(int i = 0;i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
}
}
Console.WriteLine("Enter the numbers");
int sum = 0;
int[] a = new int[5];
for (int i = 0; i < a.Length; i++)
{
a[i] = Convert.ToInt32(Console.ReadLine());
sum += a[i];
}
Console.WriteLine("The Elements are");
for(int i = 0;i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
Console.WriteLine("Sum =" + sum);
; }
C# Type Casting T
Type casting is when you assign a value of one data type to another type.
In C#, there are two types of casting:
1. Implicit Casting (automatically) - converting a smaller type to a larger type size. char -> int -> long -> float -> double
static void Main(string[] args)
{
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
Console.WriteLine(myInt);
Console.WriteLine(myDouble);
}
}
. Explicit Casting (manually) - converting a larger type to a smaller size type. double -> float -> long -> int -> char
static void Main(string[] args)
{
int myInt = 10;
double myDouble = 5.25;
bool myBool = true;
Console.WriteLine(Convert.ToString(myInt)); // Convert int to string
Console.WriteLine(Convert.ToDouble(myInt)); // Convert int to double
Console.WriteLine(Convert.ToInt32(myDouble)); // Convert double to int
Console.WriteLine(Convert.ToString(myBool));
}
Date and Time
static void Main(string[] args)
{
Console.WriteLine(DateTime.Now);
Console.WriteLine("date=" + DateTime.Now);
Console.WriteLine("date=" + DateTime.Now.ToLongDateString());
Console.WriteLine("date=" + DateTime.Now.ToShortDateString());
Console.WriteLine("date=" + DateTime.Now.ToLongTimeString());
Console.WriteLine("date=" + DateTime.Now.Year);
Console.WriteLine("date=" + DateTime.Now.Month);
Console.WriteLine("date=" + DateTime.Now.Day);
Console.WriteLine("date=" + DateTime.Now.Hour);
Console.WriteLine("date=" + DateTime.Now.Minute);
Console.WriteLine("date=" + DateTime.Now.Second);
}
String Properties
static void Main(string[] args)
{
string str = "TechnoparkTrivandrum";
Console.WriteLine(str);
Console.WriteLine("length=" + str.Length);
Console.WriteLine(str.Substring(5));
Console.WriteLine(str.Substring(3, 7));
Console.WriteLine(str.Remove(3, 4));
Console.WriteLine(str.Replace("i", "z"));
Console.WriteLine(str.PadLeft(40, '*'));
Console.WriteLine(str.PadRight(40, '*'));
}
}
· Meta Data- data about data
Math Properties
Console.WriteLine(Math.PI);
Console.WriteLine(Math.Max(5, 10));
Console.WriteLine(Math.Min(5, 10));
Console.WriteLine(Math.Sqrt(64));
Console.WriteLine(Math.Abs(-4.7));
Console.WriteLine(Math.Round(9.99));
Console.WriteLine(Math.Floor(12.6));
============================================================================
LINQ(Language Integrated Query) Array methods, such as Min, Max, and Sum, can be found in the System.Linq namespace.
static void Main(string[] args)
{
int[] myNumbers = { 5, 1, 8, 9 };
Console.WriteLine(myNumbers.Max()); // returns the largest value
Console.WriteLine(myNumbers.Min()); // returns the smallest value
Console.WriteLine(myNumbers.Sum()); // returns the sum of elements
}
int[] arr = new int[5];
Console.WriteLine("Enter 5 elements");
for (int i = 0; i < 5; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
var q = from a in arr
where a > 5
orderby a ascending
select a;
Console.WriteLine("Numbers are");
foreach (int a in q)
{
Console.WriteLine(a);
}
============================================================================
C# Methods: A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods?------- To reuse code: define the code once, and use it many times.
internal class Program
{
static void Main(string[] args)
{
MyMethod();
MyMethod();
MyMethod();
}
static void MyMethod()
{
Console.WriteLine("I just got executed!");
}
}
}
static void Main(string[] args)
{
MyMethod();
MyMethod();
MyMethod1("Devi");
MyMethod1("RAHUL");
Console.WriteLine( "Sum is " +sum(5, 6));
Console.WriteLine(sum(9, 6));
Console.WriteLine("Enter two numbers");
int c = Convert.ToInt32(Console.ReadLine());
int d = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(sum(c, d));
Console.WriteLine(area(5));
}
static void MyMethod()
{
Console.WriteLine("I just got executed!");
}
static void MyMethod1(string fname)
{
Console.WriteLine(fname + " KRISHNA");
}
static int sum(int a, int b)
{
return a + b;
}
static double area(double radius)
{
return Math.PI * radius * radius;
}
}
}
Homework
internal class Program
{
static int sum(int c,int d)
{
return c + d;
}
static int subt(int c,int d)
{
return (c - d);
}
static int multi(int c, int d)
{
return c * d;
}
static int div(int c, int d) {
return c / d;
}
static void Main(string[] args)
{
Console.WriteLine("Enter two numbers");
int a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Sum is "+sum(a,b));
Console.WriteLine("Differencs is "+subt(a,b));
Console.WriteLine("Product is "+multi(a,b));
Console.WriteLine("Division ans is "+div(a,b);
}
Array biggest element
internal class Program
{
static void Main(string[] args)
{
int[] a = { 10, 44, 22, 15 };
int biggest = 0;
for (int i = 0; i < a.Length; i++)
{
if(a[i] >=biggest)
biggest = a[i];
}
Console.WriteLine("Biggest number is:" +biggest);
}
}
MultiDImensional Array / Two-Dimensional Array
Matrix Addition
static void Main(string[] args)
{
Console.WriteLine("enter the size");
int n = Convert.ToInt32(Console.ReadLine());
int[,] a = new int[n, n];
int[,] b = new int[n, n];
int[,] c = new int[n, n];
Console.WriteLine("enter array element of a");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
a[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("enter array element of b");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
b[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("Result = ");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
c[i, j] = a[i, j]+ b[i, j];
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.WriteLine(c[i,j]);
}
}
}
Array Sorting
static void Main(string[] args)
{
int[] a = new int[5];
Console.WriteLine("enter five numbers");
for (int i = 0; i < 5; i++)
a[i] = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Ascending is : ");
Array.Sort(a);
for (int i = 0; i < 5; i++)
Console.WriteLine(a[i]);
Console.WriteLine("descending is:");
Array.Reverse(a);
for (int i = 0; i < 5; i++)
Console.WriteLine(a[i]);
}
Collection class
Array List
int i;
ArrayList a1 = new ArrayList();
Console.WriteLine("Enter ArrayList Limit");
int a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter Element");
for (i = 0; i < a; i++)
{
a1.Add(Console.ReadLine());
}
Console.WriteLine("Elements are");
foreach (var c in a1)
{
Console.WriteLine(c);
}
Threading
Thread is a unit process
Thread.Start
static void function()
{
for (int i = 11; i < 20; i++)
{
Console.WriteLine(i);
}
}
static void Main(string[] args)
{
ThreadStart childthread = new ThreadStart(function);
Thread obj = new Thread(childthread);
obj.Start();
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
}
Thread.Sleep
static void function()
{
for (int i = 11; i < 20; i++)
{
Console.WriteLine(i);
}
}
static void Main(string[] args)
{
ThreadStart childthread = new ThreadStart(function);
Thread obj = new Thread(childthread);
obj.Start();
Thread.Sleep(1000);
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
}
}
}
What is a IL?
(IL)Intermediate Language is also known as MSIL (Microsoft Intermediate Language) or CIL
(Common Intermediate Language). All .NET source code is compiled to IL. This IL is then
converted to machine code at the point where the software is installed, or at run-time by a Just-InTime (JIT) compiler.
What is a CLR?
Full form of CLR is Common Language Runtime and it forms the heart of the .NET framework
.All Languages have runtime and its the responsibility of the runtime to take care of the code execution of the program.
For example VC++ has MSCRT40.DLL,VB6 has MSVBVM60.DLL , Java has Java Virtual Machine etc. Similarly .NET has CLR.
Following are the responsibilities of CLR
· Garbage Collection :- CLR automatically manages memory thus eliminating memory leakes. When objects are not referred GC automatically releases those memory thus providing efficient memory management.
· Code Access Security :- CAS grants rights to program depending on the security configuration of the machine.Example the program has rights to edit or create a new file but the security configuration of machine does not allow the program to delete a file.CAS will take care that the code runs under the environment of machines security configuration.
· Code Verification :- This ensures proper code execution and type safety while the code runs.It prevents the source code to perform illegal operation such as accessing invalid memory locations etc.
· IL( Intermediate language )-to-native translators and optimizer’s :- CLR uses JIT and compiles the IL code to machine code and then executes. CLR also determines depending on platform what is optimized way of running the IL code.
What is a CTS?
In order that two language communicate smoothly CLR has CTS (Common Type System).
Example in VB you have “Integer” and in C++ you have “long” these datatypes are not compatible so the interfacing between them is very complicated.
In order that two different languages can communicate Microsoft introduced Common Type System. So “Integer” datatype in VB6 and “int” datatype in C++ will convert it to System.int32 which is datatype of CTS.CLS which is covered in the coming question is subset of CTS.
What is a CLS(Common Language Specification)?
This is a subset of the CTS which all .NET languages are expected to support.
It was always a dream of microsoft to unite all different languages in to one umbrella and CLS is one step towards that.
Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner
1. What is C#?
Answer: C# (pronounced "C-sharp") is a modern, object-oriented programming language developed by Microsoft as part of the .NET platform. It is designed to be simple, efficient, and flexible, providing language constructs that help to build robust and secure applications.
2. What is the .NET Framework?
Answer: The .NET Framework is a software framework developed by Microsoft that provides a runtime environment for building, deploying, and running applications on Windows. It includes the Common Language Runtime (CLR) for execution and a large class library (Base Class Library) that supports various types of applications like Windows, web, and mobile.
3. Explain the difference between managed code and unmanaged code.
Answer: Managed code is code that runs under the control of the CLR, which provides features like garbage collection, type checking, and exception handling. Unmanaged code is executed directly by the operating system outside the CLR, such as applications written in C++.
4. What is the Common Language Runtime (CLR)?
Answer: The CLR is the runtime environment in the .NET Framework that manages the execution of .NET programs. It provides memory management, security, exception handling, and garbage collection, among other services.
5. What are the main pillars of object-oriented programming (OOP)?
Answer:
Class Class is a group of similar objects. Class is a way to bind data describing an entity and appreciated function together. To create a class, use the class keyword. A Class is a blueprint of a data type. It is actually a collection of objects. It contains objects and the definition for the operation that needs to be performed on that object.
Object – It is an instance of a class.
Syntax -- Classname objectname= new classname();
namespace object1
{ class car
{
public String colour = "Red";
}
internal class Program
{
static void Main(string[] args)
{
car obj = new car();
Console.WriteLine(obj.colour);
}
}
}
Encapsulation: Bundling data and methods that operate on the data within a single unit (class).
Inheritance: Allowing a new class to inherit properties and behavior from an existing class.
Inheritance (Derived and Base Class)
In C#, it is possible to inherit fields and methods from one class to another.
We group the "inheritance concept" into two categories: Derived Class (child) - the class that inherits from another class Base Class (parent) - the class being inherited from To inherit from a class, use the : symbol. In C#, there are several types of inheritance:
In C#, there are 4 types of inheritance
1.Single Inheritance---One base class and one child class
2.Multi-Level
3.Hierarchial --- One parent and multiple child
4.Hybrid Inheritance
Syntax: class derived-class : base-class { // methods and fields }
Single inheritance
namespace inheritance
{
class vehicle
{
public void run()
{
Console.WriteLine("Running");
}
}
class car :vehicle
{
public void drive()
{
Console.WriteLine("MAruthi");
}
}
internal class Program
{
static void Main(string[] args)
{
car obj = new car();
obj.run();
obj.drive();
}
}
}
Multi-Level Inheritance
namespace inheritance
{
class vehicle
{
public void run()
{
Console.WriteLine("Running");
}
}
class car :vehicle
{
public void drive()
{
Console.WriteLine("MAruthi");
}
}
class benz : car
{
public void music()
{
Console.WriteLine("Music is PLaying");
}
}
internal class Program
{
static void Main(string[] args)
{
benz obj = new benz();
obj.run();
obj.drive();
obj.music();
}
}
}
Hierarchial Inheritance
namespace inheritance
{
class vehicle
{
public void run()
{
Console.WriteLine("Running");
}
}
class car :vehicle
{
public void drive()
{
Console.WriteLine("MAruthi");
}
}
class bus :vehicle
{
public void horn()
{
Console.WriteLine("Sound horn");
}
}
internal class Program
{
static void Main(string[] args)
{
bus obj = new bus();
car obj1 = new car();
obj1.drive();
obj1.run();
obj.horn();
obj.run();
}
}
}
Hybrid Inheritance—Combination of hierarchial and multi level inheritance
namespace inheritance
{
class vehicle
{
public void run()
{
Console.WriteLine("Running");
}
}
class car :vehicle
{
public void drive()
{
Console.WriteLine("MAruthi");
}
}
class bus :vehicle
{
public void horn()
{
Console.WriteLine("Sound horn");
}
}
class volvo : bus
{
public void travel()
{
Console.WriteLine("Travel around");
}
}
internal class Program
{
static void Main(string[] args)
{
volvo obj = new volvo();
car obj1 = new car();
obj1.drive();
obj1.run();
obj.horn();
obj.run();
obj.travel();
}
}
}
Polymorphism(many forms): Providing the ability to call the same method on different objects and have each of them respond in their own way.
Two types :
1 Function overloading
· No of parameters
· Type of parameter
· namespace polymorphism
· {
· public class TestData
·
·
·
· {
·
· public int Add(int a, int b, int c)
·
· {
·
· return a + b + c;
·
·
·
· }
·
· public int Add(int a, int b)
·
· {
·
· return a + b;
·
· }
·
· }
· internal class Program
· {
·
· static void Main(string[] args)
· {
· TestData data = new TestData();
· Console.WriteLine( data.Add(1, 2, 3));
· Console.WriteLine(data.Add(2, 5));
· }
· }
· Type of parameter
namespace polymorphism
· {
· public class TestData
·
·
·
· {
·
· public float Add(float a, float b, float c)
·
· {
·
· return a + b + c;
·
·
·
· }
·
· public int Add(int a, int b,int c)
·
· {
·
· return a + b+c;
·
· }
· public double Add(double a, double b, double c) {
· return a * b * c;
· }
·
· }
· internal class Program
· {
·
· static void Main(string[] args)
· {
· TestData data = new TestData();
· Console.WriteLine( data.Add(1.2f, 2.5f, 3.8f));
· Console.WriteLine(data.Add(2, 5,6));
· Console.WriteLine(data.Add(2.33,5.6,7.1));
· }
· }
· }
2.Function Overriding ----- Method overriding can be done using inheritance. With method overriding it is possible for the base class and derived class to have the same method name and same something.
namespace methodOverriding
{
class baseClass
{
// show() is 'virtual' here
public virtual void show()
{
Console.WriteLine("Base class");
}
}
// class 'baseClass' inherit
// class 'derived'
class derived : baseClass
{
//'show()' is 'override' here
public override void show()
{
Console.WriteLine("Derived class");
}
}
internal class Program
{
static void Main(string[] args)
{
derived obj = new derived();
obj.show();
}
}
}
Abstraction: Abstraction is a concept of simplifying a real-world object into its essential features without including background details
Hiding the complexity of code by exposing only the necessary parts.
Abstract Classes · 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 abstract class directly with the new operator. ·
Class that contains the abstract keyword with some of its methods(not all abstract method) is known as an Abstract 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 abstract methods outside the abstract class. ·
You are not allowed to declare abstract class as Sealed Class.
namespace Abstraction
{
abstract class Shape
{
// Abstract method (does not have a body)
public abstract void Draw();
// Non-abstract method
public void Display()
{
Console.WriteLine("This is a shape.");
}
}
// Derived class
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a Circle.");
}
}
// Another derived class
class Rectangle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a Rectangle.");
}
}
internal class Program
{
static void Main(string[] args)
{
Shape circle = new Circle();
Shape rectangle = new Rectangle();
// Call methods
circle.Display();
circle.Draw();
rectangle.Display();
rectangle.Draw();
}
}
}
6. What is the difference between an abstract class and an interface in C#?
Answer:
Abstract Class: Can have both abstract and non-abstract methods, properties, and fields. It is used when you want to provide some common functionality for derived classes.
Interface: Only contains declarations of methods, properties, events, or indexers. It is used to achieve full abstraction and multiple inheritance. All members are abstract by default in interfaces.
7. Explain the concept of boxing and unboxing in C#.
Answer:
Boxing: Converting a value type (e.g., int) to an object type or any interface type that it implements. It’s a process of wrapping a value type inside an object.
Unboxing: Extracting the value type from the object. This is the reverse of boxing.
8. What is the purpose of the using statement in C#?
Answer: The using statement in C# is used to ensure that resources are disposed of once they go out of scope. It is typically used for managing unmanaged resources such as file handles, database connections, etc., and is helpful for automatic disposal of objects that implement the IDisposable interface.
9. What is LINQ in C#?
Answer: LINQ (Language Integrated Query) is a set of extensions in C# that provides a querying syntax for querying data sources like collections, databases, XML, etc. It allows you to write queries directly in C# using a SQL-like syntax.
10. What is the difference between == and .Equals() in C#?
Answer:
== is a reference equality operator, and its behavior varies depending on the type. For reference types, it checks if the two references point to the same object. For value types, it checks if the values are equal.
.Equals() is used to determine if two objects have the same value, and it can be overridden in classes to provide custom equality comparison.
11. What are async and await keywords in C#?
Answer: async and await are used for asynchronous programming in C#. The async keyword is used to declare a method that performs an asynchronous operation, and await is used to suspend the execution of an async method until the awaited task completes. This helps prevent blocking the main thread.
12. What is the purpose of the Nullable<T> in C#?
Answer: Nullable<T> is a structure that allows value types to represent null values, which is typically used for database applications where fields may contain null values. For example, Nullable<int> or int? allows an integer to have a null value.
13. Explain the is and as operators in C#.
Answer:
is Operator: Checks if an object is of a particular type and returns a boolean value.
as Operator: Attempts to cast an object to a specified type. If the cast is not successful, it returns null instead of throwing an exception.
14. What is dependency injection, and why is it useful?
Answer: Dependency injection is a design pattern that allows for the injection of dependencies into a class rather than having the class create its own dependencies. This helps to decouple components, making code more modular, testable, and maintainable.
15. What is the difference between Array and ArrayList in C#?
Answer:
Array: Fixed size and strongly typed; it can only store elements of a specific type.
ArrayList: Resizable array and can store elements of different types as it stores objects, not specific types.
There are four types of access modifiers:
· Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
· Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.
· Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.
· Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.
Jagged Array-- A jagged array is an array of arrays, where each element in the main array can have a different length. In simpler terms, a jagged array is an array whose elements are themselves arrays. These inner arrays can have different lengths. Can also be mixed with multidimensional arrays. The number of rows will be fixed at the declaration time but can vary the number of columns.
int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[0][0] = 1;
jagged[1] = new int[1];
jagged[2] = new int[3] { 3, 4, 5 };
for (int i = 0; i < jagged.Length; i++)
{
int[] innerArray = jagged[i];
for (int j = 0; j < innerArray.Length; j++)
{
Console.Write(innerArray[j] + " ");
}
Console.WriteLine();
}
XML Serialisation
XML- extensible markup language
----Serialization is the process of converting an object into a stream of bytes.
namespace jaggedarray
{
public class Person
{
public string name;
public string location;
public int age;
}
internal class Program
{
static void Main(string[] args)
{
Person p = new Person();
p.name = "Reshma";
p.location = "Chengannur";
p.age = 26;
XmlSerializer x = new XmlSerializer(p.GetType());
x.Serialize(Console.Out, p);
}
}
}
Delegate-------A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. It provides a way which tells which method is to be called when an event is triggered.
Syntax ---[modifier] delegate [return_type] [delegate_name] ([parameter_list]);
namespace @delegate
{
public delegate double mydelegate(int a, int b);
internal class Program
{
static double myfun(int x, int y)
{
return x * y;
}
static void Main(string[] args)
{
mydelegate del = new mydelegate(myfun);
Console.WriteLine("Please enter two numbers");
int P = Convert.ToInt32(Console.ReadLine());
int Q = Convert.ToInt32(Console.ReadLine());
double res = del(P, Q);
Console.WriteLine("Result:" + res);
}
}
}
Break----The break statement can also be used to jump out of a loop.
internal class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
break;
}
Console.WriteLine(i);
}
}
}
Continue--- The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop
internal class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
continue;
}
Console.WriteLine(i);
}
o/p—12356789
internal class Program
{
static int sum(int c,int d)
{
return c + d;
}
static int subt(int c,int d)
{
return (c - d);
}
static int multi(int c, int d)
{
return c * d;
}
static int div(int c, int d) {
return c / d;
}
static void Main(string[] args)
{
Console.WriteLine("Enter two numbers");
int a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter a sign");
String c=Console.ReadLine();
switch (c)
{
case "+":
Console.WriteLine("Sum is " + sum(a, b));
break;
case "-":
Console.WriteLine("Differencs is " + subt(a, b));
break;
case "*":
Console.WriteLine("Product is " + multi(a, b));
break;
case "/":
Console.WriteLine("Division ans is " + div(a, b));
break;
default:
Console.WriteLine("INvalid Operator");
break;
C# - What is OOP?
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or methods that perform operations on the data, while object-oriented programming is about creating objects that contain both data and methods. Object-oriented programming has several advantages over procedural programming:
OOP is faster and easier to execute OOP provides a clear structure for the programs
OOP is faster and easier to execute OOP provides a clear structure for the programs
THE FOLLOWINGS ARE THE FEATURES OF OOPS:
1.Class
2.Objects
3.Encapsulation
4.Abstraction
5.Inheritance
6.polymophism
Class -class is a group of similar objects.Class is a way to bind data describing an entity and assossiated functions together. Object –object is an identifier entity that have some characteristics and behavior. Abstraction-It is a concept of simplifying a real world object into its essential features without including background details.
Encapsulation-Wrapping up of data into single unit is known as encapsulation. Inheritance –It is a property of inheriting properties of one class to another.
Polymorphism-The word polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'.
Polymorphism can be static or dynamic.
In static polymorphism, the response to a function is determined at the compile time.
In dynamic polymorphism, it is decided at run-time.
POLYMORPHISM-"Poly" means many and "morph" means forms. Polymorphism provides the ability to a class to have multiple implementations with the same name.
Class Syntax Classname objectname= new classname(); Eg: Program p= new Program();
Encapsulation(Data Hiding)
Encapsulation is an object-oriented programming concept that allows programmers to wrap data and code snippets inside an enclosure. By using the encapsulation program, you can hide the members of one class from another class. It’s like encircling a logical item within a package. It allows only relevant information available and visible outside and that too only to specific members.Encapsulation is implemented by using access specifiers.
Access Specifier is used for defining the visibility and accessibility of the class member in C#.
C# contains the following access specifiers
• Public
• Private
• Protected
• Internal
Public: The public keyword allows its members to be visible from anywhere inside the project. This access specifier has the least visibility restriction.
Private: The private members can only be accessed by the member within the same class. This has one of the most restricted visibility.
Protected: Protected accessibility allows the member to be accessed from within the class and from another class that inherits this class.
Internal: Internal provides accessibility from within the project.
Private
namespace Encapsulation__private
{
class Program
{
private string model;
static void Main(string[] args)
{
Program p = new Program();
p.model = "BMW";
Console.WriteLine(p.model);
}
}
}
Public
namespace encap_public
{
class Car
{
public string model = "Mustang";
}
internal class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}
}
Protected
namespace encap_protected
{
class X
{
// Member x declared
// as protected
protected int x;
public X()
{
x = 10;
}
}
class Y : X
{
public int getX()
{
return x;
}
}
internal class Program
{
static void Main(string[] args)
{
Y obj2 = new Y();
// Displaying the value of x
Console.WriteLine("Value of x is : {0}", obj2.getX());
}
}
}
Internal
namespace encP_INTERNAL
{
class access
{
// String Variable declared as internal
internal string name;
public void print()
{
Console.WriteLine("\nMy name is " + name);
}
}
internal class Program
{
static void Main(string[] args)
{
access ac = new access();
Console.Write("Enter your name:\t");
// Accepting value in internal variable
ac.name = Console.ReadLine();
ac.print();
Console.ReadLine();
}
}
}
Polymorphism
POLYMORPHISM-"Poly" means many and "morph" means forms.
Polymorphism provides the ability to a class to have multiple implementations with the same name. Types of Polymorphism
There are two types of polymorphism in C#:
Static / Compile Time Polymorphism.(function overloading)
Dynamic / Runtime Polymorphism.(function overriding)
Function Overloading(Method Overloading)
Method overloading is an example of Static Polymorphism. In overloading, the method / function has a same name but different signatures.
namespace overloading
{
public class TestData
{
public int Add(int a, int b, int c)
{
return a + b + c;
}
public int Add(int a, int b)
{
return a + b;
}
}
internal class Program
{
static void Main(string[] args)
{
TestData dataClass = new TestData();
int add2 = dataClass.Add(45, 34, 67);
int add1 = dataClass.Add(23, 34);
Console.WriteLine(add2);
Console.WriteLine(add1);
}
}
}
Method overriding can be done using inheritance. With method overriding it is possible for the base class and derived class to have the same method name and same something.
namespace overriding
{
public class Drawing
{
public virtual double Area()
{
return 0;
}
}
public class Circle : Drawing
{
public double Radius { get; set; }
public Circle()
{
Radius = 5;
}
public override double Area()
{
return (3.14) * Math.Pow(Radius, 2);
}
}
public class Square : Drawing
{
public double Length { get; set; }
public Square()
{
Length = 6;
}
public override double Area()
{
return Math.Pow(Length, 2);
}
}
public class Rectangle : Drawing
{
public double Height { get; set; }
public double Width { get; set; }
public Rectangle()
{
Height = 5.3;
Width = 3.4;
}
public override double Area()
{
return Height * Width;
}
}
internal class Program
{
static void Main(string[] args)
{
Drawing obj1 = new Circle();
Console.WriteLine("Area :" + obj1.Area());
Drawing obj2 = new Square();
Console.WriteLine("Area :" + obj2.Area());
Drawing obj3 = new Rectangle();
Console.WriteLine("Area :" + obj3.Area());
}
}
}
Interface
In C#, an interface is a fundamental concept defining a contract or a set of rules a class must adhere to. It specifies a list of methods, properties, events, or indexers a class implementing the interface must provide. Interfaces allow you to define a common set of functionality that multiple classes can share, promoting code reusability and ensuring a consistent structure for related classes.
An interface is also a user-defined data type.
namespace @interface
{
interface ITestInterface1
{
void Add(int num1, int num2);
}
interface ITestInterface2 : ITestInterface1
{
void Sub(int num1, int num2);
}
public class ImplementationClass1 : ITestInterface1
{
//Implement only the Add method
public void Add(int num1, int num2)
{
Console.WriteLine($"Sum of {num1} and {num2} is {num1 + num2}");
}
}
public class ImplementationClass2 : ITestInterface2
{
//Implement Both Add and Sub method
public void Add(int num1, int num2)
{
Console.WriteLine($"Sum of {num1} and {num2} is {num1 + num2}");
}
public void Sub(int num1, int num2)
{
Console.WriteLine($"Difference of {num1} and {num2} is {num1 - num2}");
}
}
internal class Program
{
static void Main(string[] args)
{
ImplementationClass1 obj1 = new ImplementationClass1();
//Using obj1 we can only call Add method
obj1.Add(10, 20);
//We cannot call Sub method
//obj1.Sub(100, 20);
ImplementationClass2 obj2 = new ImplementationClass2();
//Using obj2 we can call both Add and Sub method
obj2.Add(10, 20);
obj2.Sub(100, 20);
}
}
}
namespace @interface
{
interface ITestInterface1
{
void Add(int num1, int num2);
}
interface ITestInterface2 : ITestInterface1
{
void Sub(int num1, int num2);
}
public class ImplementationClass1
{
//Implement only the Add method
public void Add(int num1, int num2)
{
Console.WriteLine($"Sum of {num1} and {num2} is {num1 + num2}");
}
}
public class ImplementationClass2 : ITestInterface2,ITestInterface1
{
//Implement Both Add and Sub method
public void Add(int num1, int num2)
{
Console.WriteLine($"Sum of {num1} and {num2} is {num1 + num2}");
}
public void Sub(int num1, int num2)
{
Console.WriteLine($"Difference of {num1} and {num2} is {num1 - num2}");
}
}
internal class Program
{
static void Main(string[] args)
{
ImplementationClass1 obj1 = new ImplementationClass1();
//Using obj1 we can only call Add method
obj1.Add(10, 20);
//We cannot call Sub method
//obj1.Sub(100, 20);
ImplementationClass2 obj2 = new ImplementationClass2();
//Using obj2 we can call both Add and Sub method
obj2.Add(10, 20);
obj2.Sub(100, 20);
}
}
}
No comments:
Post a Comment