C
being the procedural language while C#
is a more object-oriented language. The biggest difference is that C# supports automatic garbage collection by Common Language Runtime (CLR) while C does not. C# primarily needs a .NET framework to execute while C is a platform-agnostic language. // hello, this is a single line comment
/* Hello this is a multiline comment
last line of comment*/
/// Hello this is XML comment
// Boxing
int anum = 123;
Object obj = anum;
Console.WriteLine(anum);
Console.WriteLine(obj); ​
// Unboxing
Object obj2 = 123;
int anum2 = (int)obj;
Console.WriteLine(anum2);
Console.WriteLine(obj);
float, int, byte, double, etc.
). But if you use it beside int it has to be cast.enum Dow {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
Break | Continue |
---|---|
You can use break statements in both switch and loop (for, while, and do-while ) statements. | You can use continue statements only in the loop (for, while, do) statements. |
The switch or loop statements terminate at the moment the break statement is executed and it ends abruptly from there. | You cannot make a continue statement terminate the loop, it carries on the loop to go to the next iteration level without executing the immediate next step. |
The loop or switch exits immediately from the inner loop when the compiler encounters a break statement and comes out of the inner loop. | A continue that is placed inside a nested loop within a switch causes the next loop iteration. |
try {
//exception handling starts with try block
} catch( ExceptionName ea1 ) {
// errors are handled within the catch block
} catch( ExceptionName e2 ) {
// more catch block
} catch( ExceptionName eN ) {
// more catch block to handle multiple exception raised
} finally {
// last block of the exception handling
}
~
) symbol.~class_name()
{
//code
}
void Method(ref int refArgument)
{
refArgument = refArgument + 10;
}
int number = 1;
Method(ref number);
Console.WriteLine(number);
// Output: 11
public static string GetNextFeature(ref int id)
{
string returnText = "Next-" + id.ToString();
id += 1;
return returnText;
}
public static string GetNextFeature(out int id)
{
id = 1;
string returnText = "Next-" + id.ToString();
return returnText;
}
// C# program to illustrate the concept
// of the extension methods
using System;
namespace ExtensionMethod {
static class NewMethodClass {
// Method 4
public static void M4(this Scaler s)
{
Console.WriteLine("Method Name: M4");
}
// Method 5
public static void M5(this Scaler s, string str)
{
Console.WriteLine(str);
}
}
// Now we create a new class in which
// Scaler class access all the five methods
public class IB {
// Main Method
public static void Main(string[] args)
{
Scaler s = new Scaler();
s.M1();
s.M2();
s.M3();
s.M4();
s.M5("Method Name: M5");
}
}
}
If(any condition)
{
//code to be executed if the condition returns true
}
If(condition)
{
//code to be run if the condition is true
}
Else
{
//code to be run if the if-condition is false
}
If (condition to be checked)
{
//code
If(condition 2)
{
//code for if-statement 2
}
}
If(condition 1 to be checked)
{
//code for condition 1
}
Else (condition 2 to be checked)
{
//code for condition 2
}
Else
{
//code will run if no other condition is true
}
Clone()
method, we creates a new array object containing all the elements in the original Array and using CopyTo()
method. All the elements of existing array copies into another existing array. Both methods perform a shallow copy. Dispose()
is called when we want for an object to release any unmanaged resources with them. On the other hand, Finalize()
is used for the same purpose, but it doesn’t assure the garbage collection of an object. public partial Class_name
{
// Code
}
sealed class class_name
{
// data members
// methods
.
.
.
}
static void Main(string[] args)
{
string[] languages = { "C#", "Python", "Java" };
foreach(string s in languages)
{
if(System.Text.RegularExpressions.Regex.IsMatch(s,"Python"))
{
Console.WriteLine("Match found");
}
}
}
Public delegate void deathInfo();
Public event deathInfo deathDate;
//Replacing with Action//
Public event Action deathDate;
Func <int, string, bool> myDel is same as delegate bool myDel(int a, string b);
Predicate<string> myDel is same as delegate bool myDel(string s);
System.Runtime.Serialization
can contain classes for serialization.Xsd.exe
tool converts the files to the XSD
format. During Serialization of C#
code, the classes are converted to XSD compliant format by xsd.exe.System.Threading.ThreadPool
namespace has classes that manage the threads in the pool and its operations.System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(SomeTask));
lock(ObjA)
means the lock is placed on ObjA until this process releases it, no other thread can access ObjA.WaitOne()
is used to lock and ReleaseMutex()
is used to release the lock. But Mutex is slower than lock as it takes time to acquire and release it.Monitor.Enter
and Monitor.Exit
implements lock internally. a lock is a shortcut for Monitors. lock(objA)
internally calls.try
{
GetAllData();
}
catch(Exception ex){
}
Hashtable HT = new Hashtable ();
C#
includes three keywords that support runtime type identification : is, as, and typeof. expr is type
expr as type
int[] intArray;​
[]
) and the name of the array.int[] intArray;
intArray = new int[5];
int[] intArray;
intArray = new int[100];
< modifier > <
return type > this[argument list] {
get {
// your get block code
}
set {
// your set block code
}
} ​
<modifier>
<return type>
Equals()
method are used to compare two value type data items or reference type data items. The Equality Operator (==) is the comparison operator and the Equals()
method compares the contents of a string. The == Operator compares the reference identity while the Equals()
method compares only contents. Let’s see with some examples.Equals()
method.using System;
namespace ComparisionExample {
class Program {
static void Main(string[] args) {
string name = "sandeep";
string myName = name;
Console.WriteLine("== operator result is {0}", name == myName);
Console.WriteLine("Equals method result is {0}", name.Equals(myName));
Console.ReadKey();
}
}
}
class IB {
// Constant fields
public const int xvar = 20;
public const string str = "InterviewBit";
// Main method
static public void Main()
{
// Display the value of Constant fields
Console.WriteLine("The value of xvar: {0}", xvar);
Console.WriteLine("The value of str: {0}", str);
}
}
Output :
The value of xvar is 20.
The value of string is Interview Bit
public readonly int xvar1;
public readonly int yvar2;
// Values of the readonly
// variables are assigned
// Using constructor
public IB(int b, int c)
{
xvar1 = b;
yvar2 = c;
Console.WriteLine("The value of xvar1 {0}, "+
"and yvar2 {1}", xvar1, yvar2);
}
// Main method
static public void Main()
{
IB obj1 = new IB(50, 60);
}
}
Output :
The value of xvar1 is 50, and yvar2 is 60
string s = string.Empty;
for (i = 0; i < 1000; i++)
{
s += i.ToString() + " ";
}
StringBuilder sb = new StringBuilder();
for (i = 0; i < 1000; i++)
{
sb.Append(i); sb.Append(' ');
}
Class Name | Description |
---|---|
FileStream | This stream read from and write to any location within a file |
BinaryReader | read primitive data types from a binary stream |
DirectoryInfo | perform operations on directories |
FileInfo | perform operations on files |
BinaryWriter | write primitive data types in binary format |
StreamReader | to read characters from a byte Stream |
StreamWriter | write characters to a stream. |
StringReader | read from a string buffer |
StringWriter | write into a string buffer |
int? i = null;
var? i = null;
public async Task>CalculateCount()
{
await Task.Delay(2000);
return 1;
}
public async task mytestmethod()
{
Task> count = CalculateCount();
int result = await count;
}
CalculateCount()
. CalculateCount()
starts execution and calculates something.type Book = struct
val title : string
val author: string
val price : float
new (title, author, price) = // Constructor
{title = title; author = author; price = price;}
end
let book = new Book("FSharp Programming", "Chris Smith", 100.0) // Calling Constructor
printfn "Title : %s " book.title
printfn "Author : %s" book.author
printfn "Price : $%0.2f" book.price
type Calcualte =
| Add of val1 : int * val2 : int
| Multiply of val1 : int * val2 : int
let compute vall =
match vall with
| Add (val1, val2) -> val1+val2
| Multiply (val1, val2)->val1*val2
let addition = compute (Add(10,10))
let multiplication = compute (Multiply(2,5))
printf "Addition = %d\nMultiplication = %d" addition multiplication