Sei sulla pagina 1di 70

R4R provide basic C# Tutorials concept with C# Examples . Through R4R you can develop C# programming concept.

R4R provide C# Interview Questions with answers.R4R provide C# Languages study materials in easy way.

C# Tutorials
1.1 C# Basic Tutorials (Examples)

C# Examples
2.1 C# Basic Examples

C# Interview Questions with Answers


3.1 3.2 3.3 3.5 3.5 C# C# C# C# C# Subjective Questions with Answers Interview Questions with Answers Objective Questions And Answers Basics Questions & Answers FAQS

Introduction to .NET Technology


.Net Technology is developed by Microsoft in 2000. .Net technology is the new addition to Windows. The .NET ("dot - net") environment is effectively a "virtual computer" that runs on a real computer, through which a developers can create a .NET application in any .NET compatible language and participate in the same software project writing code in the .NET languages in which (such as Visual C++.NET, Visual Basic .NET, C#, Java, J# and more others). .NET Core Technology- .NET Technology has quite a few different parts Common Language Runtime (CLR) Common Language Infrastructure (CLI) Common Language Specification (CLS) .NET Framework tools (examples include gacutil, sn, and all the compilers) .NET Framework is FREE (including the compilers!) .NET development is made MUCH easier by using Visual Studio .NET

Introduction of .NET Framework.NET Framework is a software framework developed by Microsoft for Microsoft Windows operating systems. .NET Framework has a large library, and it supports several programming languages which allows language interoperability (each language can use code written in other languages.) Features of framework's Base Class Library User Interface Web Application Development and

Database Connectivity Data Access Network Communications. Cryptography

The class library is used by programmers, who combine it with their own code to produce applications. Versions of .NET FrameworksVersion 1.0 1.1 2.0 3.0 Version Number Release Date 1.0.3705.0 1.1.4322.573 2.0.50727.42 3.0.4506.30 13-02-2002 24-04-2003 07-11-2005 06-11-2006 Visual Studio Framework Operating System Windows Server Visual Studio .NET 2003 Visual Studio .NET Windows Server 2003 2003 Visual Studio Windows Server 2005 2003 R2 Windows Vista, Visual Studio Windows Server 2005 2008 Windows 7, Visual Studio Windows Server 2008 2008 R2 Windows 7, Visual Studio Windows Server 2010 2008 R2

3.5

3.5.21022.8

19-11-2007

4.0

4.0.30319.1

12-04-2010

Architecture of .NET Framework-

History of C# C#(C Sharp) was designed for developing application in a fully object-oriented manner as part of the Microsoft .NET initiative. C# debuted in the year 2000 by Microsoft founder Bill Gates. At the same time, Visual Studio .NET was announced. C# is an object-oriented programming language as part of their .NET initiative in response to the success of Sun Microsystems' Java programming language. C# source codeas well as those of other .NET languagesis compiled into an intermediate byte code called MSIL (Microsoft Intermediate Language. C# is primarily derived from the C, C++, and Java programming languages with some features of Microsoft's Visual Basic in the mix. C# is used to develop applications like Console Application Window Base Application Web Based Application Mobile Application

.NET offers an alternative to Java development. Microsoft's Visual Studio .NET development environment incorporates several different languages including ASP.NET, C#, C++, and J# (Microsoft Java for .NET), all of which compile to the Common Language Runtime. Why C# is better than other languagesC# and Java- Here are some features that C# has but Java does not:

1. Delegates- You can kind of do this in Java, but its not as clean. 2. Lambdas- Which are way better than anonymous inner classes. (C# has anonymous 3. 4. 5. 6. 7. 8.

inner classes, too.) LINQ (Language Integrated and Query ) Operator overloading- This feature can be abused, but it is still occasionally useful, especially in libraries and DSLs. Properties- No need to write getters and setters. Everything looks like a direct field access, even if it isnt. Yield CO-Routine capability- This is a powerful and highly useful capability, especially for lazy iterators. Extension methods- They permit you to extend existing classes. Null coalescing operator that provides a simple syntax for dereferencing a reference and supplying a default if the reference is null.

C# and VB

1. C# is a new, type-safe language, object-oriented language. It has automatic garbage


collection feature. It is developed solely for running along with CLR frameworks. We can use pointers, if needed, though unsafe. On the other hand, VB.NET is developed from VB. Comments in C# are just better. You can do Multiline comments, XML comments, single line comments, etc. Regions in C# are far better. The key here is that you can place a region inside a function, thus breaking up the implementation into logical pieces.

2. 3.

C# and C++

1. 2. 3. 4. 5.

C++ C++ C++ C++ C++

too complex and unsafe system-dependent not Web-ready does not manage memory has pointer types

Conclusion C# nicely improved on Java, VB and C++. C# can be used for everything like -sockets, threading, events, sql, XML. C# by Dissection: a plug Parallel treatment

Advance features of C# 1.LINQ (Language Integrated and Query)-

LINQ to SQL LINQ to OBJECT

2. XML Web Services 3. Cryptography Most Important Advantages of C# -

1. 2. 3. 4. 5. 6. 7. 8.

C# is supported by Microsoft. C# is type safe which comes with its advantages. Nothing is better when you are developing windows applications. Its syntax is also very well designed. Code looks pretty good. Its intelligence IDE Its worth learning because lots of code is written and is being written in it. It feels so good when you code in C# in Visual Studio. With C# you can explore lots of interesting things .NET,WPF,WCF,XNA,ASP.NET

C# Tutorial with Example 1. .NET FUNDAMENTAL 2. C# FUNDAMENTAL 3. Hello Word 4. Display Hello World using int Main in C# 5. Input a Number and sum it using C# 6. Command Line Argument Using C# 7. Command Line Argument :- PASSING multiple VALUES AT RUN TIME 8. Input a Number and sum it using C# 9. PASSING number as command line argument and display sum of the numbers 10. Typecasting in C# 11. Initialize Constant at Declaration Time in C# 12. Call Private Data C# 13. How to Define Class and Object Using C# 14. Sealed class example in C# 15. Parameter Modifiers example in C# 16. Example of Structure with Constructor in C# 17. Boxing In C# 18. Boxing and Unboxing in C# 19. UnBoxing example in C# 20. Example Constructor In C# 21. Example of Single Inheritance in C# 22. Multilevel Inheritance Example C# 23. Multicast Delegates Using C# 24. Example of Method Overloading Using C# 25. Method Overriding Using C# 26. Example of Inheritance and Constructor in C# 27. Implementation Of Get & Set Property Using C# 28. Display public attribute with public method

29. Example of Structure in C# 30. Example of Readonly keyword in C# 31. Example of define Get and Set Using C# 32. Return More Then One Value C# 33. Example of Interface in C# 34. Create an array of object and Define Indexers in C# 35. Example Of Enumeration in C# 36. Example of Delegate Declaration in C# 37. Example Array in C# 38. Example of Abstract class in C# 39. .NET FUNDAMENTAL 40. In this section we are going to explain about .net fundamentals 41. What is .NET? 42. .NET is a FRAMEWORK/ SPECIFICATION/ SET OF RULES/ GUIDELINES for
INTERNET PROGRAMMING According to MS WHITEPAPER .NET Definition? ================== It is a kind of framework to move from desktop centric environment( stand alone applications ) to web centric environment (Word Wide) . MS WHITEPAPER ================== It is first page of Micro Soft .Net documentations. What is difference between J2EE and .NET .NET 1)SUPPORT OF MULTIPLE LANG(57 LANG) 2)STRONG & SMART IDE 3)COMPILED 4)FASTER 5)POINTER / OPR. OVERLODING *Use of C# in developing (os-windows-2003 c#)

43. 44. 45.

J2EE 1)ONLY JAVA CAN BE USED AS LANG. 2)NO IDE(INTIGRATED DEVE LOPMENT ENVIRONMENT) 3)INTERPRETED LANG 4)SLOW 5)NO POINTER/ NO OPERTor OVERLODING

46. ====================================================
======= .NET TERMS:============ 1).NET EXPERIENCE:- FOR END USER (CLIENT) 2).NET PLATFORM :- FOR PROGRAMMER A)CLS(COMMON LANG SPECIFICATION):-COMMON GUIDELINE FOR ALL LANG.

*BCL(BASE CLASS LIBRARY)/upc(UNIFIED PRIMARY CLASS):- CLASSES WILL BE COMMON FOR ALL **CTS(COMMON TYPE SPECIFICATION) :- DATA TYPE WILL BE SAME B)CLR(COMMON LANG RUNTIME) IT IS A KIND OF RUN TIME ENVIRONMENT. C)WEB SERVICES(ASP.NET) This is used to create web page.

47. We will explain more about theses all terms in more detail in next sections
.NET ARCHITECTURE:-

48. The this section we are going to explain the architecture of .net and its working. As 49.

we can see in following figure. In this figure we have explain the steps of .net and its architecture. 1: Every language has its own compiler .Like C#,VB,other language has a compiler . C# has a compiler csc(c# compiler) and vbc(visual basic compiler).These compiler are used to convert the source code into msil and clr(common language runtime) read msil and convert into .exe file .The .exe file is used to execute our program. ================= C# VB.NET ANY | | | CSC VBC COMPILER --------------------------------| M S I L (MICROSOFT INTERMEDIATE LANG) ----------------------------------| CLR --------------------------------.EXE .EXE .EXE ====================================================

C# FUNDAMENTAL
C# ======================= It is a a kind of .net compatible object oriented, event driven programming language. It is the mother language of .net Types of C# programming:-There are two type of C# programming

================== 1)Console Programming:-It write on notepad and run on command prompt Visual Studio.net . 2)Windows Programming:-It write and run on Visual Studio.net ========================================================= =========== How to write and run console programming:1)Open notepad and write the program.

class HelloWorld { public static void Main() { System.Console.WriteLine("Hello World"); } }

2)Open command prompt Of Visual Studio.net 3)Write your program in notepad and save it with extension .cs eg "HellOWord.cs" 4)To Compile on command prompt c:\>csc HellOWord.cs(NameofProgram.cs) 5.To run c:\>HellOWord(NameofProgram)

C# Examples

Hello world Using C#

class HelloWorld { public static void Main() { System.Console.WriteLine("Hello World"); } } Download Source Code

Display Hello World using int Main in C#

class ExampleIntMain { public static int Main() { System.Console.WriteLine("hello world"); return 0; } } Download Source Code

Example to input Name Using C#

//Example to input Name Using C# using System; class x { public static void Main() { Console.WriteLine("Enter Name --->"); String nm=System.Console.ReadLine(); Console.WriteLine("The Name is --->"+nm); } } Download Source Code

Command Line Argument Using C#

//Command Line Argument :- PASSING VALUES AT RUN TIME using System; class x { public static void Main(String[] args)

{ Console.WriteLine("The name is --->"+args[0]); } } Download Source Code

Command Line Argument :- PASSING multiple VALUES AT RUN TIME

//Command Line Argument :- PASSING multiple VALUES AT RUN TIME using System; class x { public static void Main(String[] args) { for(int i=0;i<args.Length;i++) { Console.WriteLine("The name is --->"+args[i]); } } } Download Source Code

Input a Number and sum it using C#

//To input number:-Sum in C# using System; class x { public static void Main() { Console.WriteLine("Enter Number --->"); String n=System.Console.ReadLine(); String m=System.Console.ReadLine(); int sum=Int32.Parse(n)+Int32.Parse(m); Console.WriteLine("The sum is --->"+sum);

} }

Download Source Code

PASSING number as command line argument and display sum of the numbers

//Command Line Argument :- PASSING number as command line argument and display sum of the number using System; class x { public static void Main(String[] args) { int n=Int32.Parse(args[0]); int m=Int32.Parse(args[1]); int sum=n+m; Console.WriteLine("The sum is --->"+sum); } } Download Source Code

Typecasting in c#

//Typecast Using C# class Typecast { public static void Main() { char c='x'; byte b=50; short s=1996; int i=123456789; long l=1234567896789L; float f1=3.142F; double d1=0.0000000987;

System.Console.WriteLine("variabel created"); System.Console.WriteLine("c=" + c); System.Console.WriteLine("b=" + b); System.Console.WriteLine("s=" + s); System.Console.WriteLine("i =" + i); System.Console.WriteLine("l=" + l); System.Console.WriteLine("f1=" + f1); System.Console.WriteLine("d1=" + d1); System.Console.WriteLine(" "); System.Console.WriteLine("type casting"); short s1=(short)b; short s2=(short)i; //incorrect result float n1=(float)l; int m1=(int)f1; //fractional is lost System.Console.WriteLine("(short)b=" + s1); System.Console.WriteLine("(short)i=" + s2); System.Console.WriteLine("(float)l =" + n1); System.Console.WriteLine("(int)f1 =" + m1); } } Download Source Code

Initialize Constant at Declaration Time

// Initialize Constant at Declaration Time in C# using System; public class ConstTest { class MyClass { public int x; public int y; public const int c1 = 5; public const int c2 = c1 + 5; public MyClass(int p1, int p2) { x = p1; y = p2; } } public static void Main() { MyClass mC = new MyClass(11, 22); Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y); Console.WriteLine("c1 = {0}, c2 = {1}", MyClass.c1, MyClass.c2 ); } }

Download Source Code

Call Private Data C#

//To call the private data member we can use public method class a { private int k; //Public method public void display() { k=1000; System.Console.WriteLine("The value of k is -->"+k); } //Method with parameter public void display1(int p) { k=p; System.Console.WriteLine("The value of k is -->"+k); } } class b { public static void Main() { a x=new a(); x.display(); x.display1(3413); } } Download Source Code

How to Define Class and Object Using C#

//How to Define Class and Object class a { //method public void display() {

System.Console.WriteLine("Hello"); } } class b { public static void Main() { a x=new a(); // x is object of class a x.display(); } }

Download Source Code

Sealed class example in C#

/*Sealed class:A sealed class cannot be inherited. Sealed class example in c# */ using System; public sealed class MyClass { public int x; public int y; } class a : MyClass { public void display() { System.Console.WriteLine("Hello"); } } class MainClass { public static void Main() { MyClass mC = new MyClass(); mC.x = 110; mC.y = 150; Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y); } } Download Source Code

Parameter Modifiers example in C#

/*Parameter Modifiers example in C#:params:-To pass any number of parameter */ using System; public class MyClass { public static void a(params int[] list) { for ( int i = 0 ; i < list.Length ; i++ ) Console.WriteLine(list[i]); } public static void b(params object[] list) { for ( int i = 0 ; i < list.Length ; i++ ) Console.WriteLine(list[i]); Console.WriteLine(); } public static void Main() { a(1, 2,888,99, 3,44,55,66); b(1, 'a', "test"); int[] myarray = new int[3] {10,11,12}; a(myarray); } } Download Source Code

Example of Structure with Constructor in C#

//Structure with constructor struct a { private int x; public a(int y) { x=y; } public void display() { System.Console.WriteLine("x="+x); } } class b { public static void Main() { a t=new a(333); t.display(); } }

Download Source Code


Boxing In C# using System; class TestBoxing { public static void Main() { int i = 123; object o = i; // Implicit boxing i = 456; // Change the contents of i Console.WriteLine("The value-type value = {0}", i); Console.WriteLine("The object-type value = {0}", o); } }

Download Source Code

Boxing and Unboxing in C#

using System; class TestBoxing { public static void Main() { int i = 123; object o = i; // Implicit boxing i = 456; // Change the contents of i Console.WriteLine("The value-type value = {0}", i); Console.WriteLine("The object-type value = {0}", o); } } Download Source Code

UnBoxing example in C#

//UnBoxing example in C# using System; public class UnboxingTest { public static void Main() { int intI = 123; // Boxing object o = intI; //Unboxing int intJ = (int) o; Console.WriteLine("Unboxing OK."); } }

Download Source Code

Example Constructor In C#

/*Constructor :-

1)It is used to initialize the private attribute of class 2)It is just like method 3)Class name and Constructor name must be same 4)constr can be overloaded 5)Cosntr can be parameterized 6)we don't need to call it. 7)call automatically at the time of object creation 8)when we r not defining any Constructor there will be a default Constructor 9)we don't use any return type */ class a { private int k; //Constructor Overloading public a()//Constructor { k=1000; } public a(int p)//parameterized Constructor { k=p; } //Public method public void display() { System.Console.WriteLine("The value of k is -->"+k); } } class b { public static void Main() { a x=new a(); x.display(); a y=new a(42432) ; y.display(); } }

Download Source Code

Example of Single Inheritance in C#

//Single Inheritence example in C# class a { public void display() { System.Console.WriteLine("hahahaha"); } } class b : a //b is child of a { public void display1() { System.Console.WriteLine("hihihih"); } } class c { public static void Main() { b x=new b();//Normally object of child x.display(); x.display1(); } } Download Source Code

Multilevel Inheritance Example C#

//Multilevel Inheritance Example C# class a { public void display() { System.Console.WriteLine("hahahaha"); } }

class b : a //b is child of a { public void display1() { System.Console.WriteLine("hihihih"); } } class d : b //d is child of b { public void display2() { System.Console.WriteLine("hohohohoh"); } } class c { public static void Main() { d x=new d();//Normally object of child x.display(); x.display1(); x.display2(); } } Download Source Code

Multicast Delegates Using C#

//Multicast Delegates:- when a Delegates contain reference of multiple function using System; delegate void MyDelegate(string s); class MyClass { public static void Hello(string s) { Console.WriteLine(" Hello, {0}!", s); } public static void Goodbye(string s) { Console.WriteLine(" Goodbye, {0}!", s); }

public static void Main() { MyDelegate a, b, c, d; // Create the delegate object a that references // the method Hello: a = new MyDelegate(Hello); // Create the delegate object b that references // the method Goodbye: b = new MyDelegate(Goodbye); // The two delegates, a and b, are composed to form c: c = a + b; // Remove a from the composed delegate, leaving d, // which calls only the method Goodbye: d = c - a; Console.WriteLine("Invoking a("A"); Console.WriteLine("Invoking b("B"); Console.WriteLine("Invoking c("C"); Console.WriteLine("Invoking d("D"); } } Download Source Code delegate a:"); delegate b:"); delegate c:"); delegate d:");

Example of Method Overloading Using C#

//Method Overloading:- same name,different signature,same class class a { private int k; //Public method public void display() { k=1000; System.Console.WriteLine("The value of k is -->"+k); } //Method with parameter public void display(int p) { k=p; System.Console.WriteLine("The value of k is -->"+k); } } class b {

public static void Main() { a x=new a(); x.display(); //upper x.display(3413); } }

Download Source Code

Method Overriding Using C#

//Method Overriding:-same name / same signature class a { public virtual void display() { System.Console.WriteLine("Method Overriding Using C#:A Class "); } } class b : a //b is child of a { public override void display() { System.Console.WriteLine("Method Overriding Using C#:B Class "); } } class d : b //d is child of b { public override void display() { System.Console.WriteLine("Method Overriding Using C#:D Class "); } } class c { public static void Main() { d x=new d();//Normally object of child x.display();

} }

Download Source Code

Example of Inheritance and Constructor in C#

//Inheritance and constructor in C# class a { public a() { System.Console.WriteLine("constr a"); } public virtual void display() { System.Console.WriteLine("A"); } } class b : a //b is child of a { public b() { System.Console.WriteLine("constr b"); } public override void display() { System.Console.WriteLine("B"); } } class d : b //d is child of b { public d() { System.Console.WriteLine("constr d"); } public override void display() { System.Console.WriteLine("D"); } } class c

{ public static void Main() { d x=new d();//Normally object of child x.display(); } } /* constr calling:- top to bottom method :- bottom to top */

Download Source Code

Implementation Of Get & Set Property Using C#

//Example to input Name Using C# using System; class x { public static void Main() { Console.WriteLine("Enter Name --->"); String nm=System.Console.ReadLine(); Console.WriteLine("The Name is --->"+nm); } } Download Source Code

Display public attribute with public method

//Display public attribute with public method class a { public int k; //attribute

//Public method public void display() { System.Console.WriteLine("R4R"); } } class b { public static void Main() { //Object of class a a x; x=new a(); x.display(); x.k=100; System.Console.WriteLine(x.k); } } Download Source Code

Example of Structure with Constructor in C#

//Structure with constructor struct a { private int x; public a(int y) { x=y; } public void display() { System.Console.WriteLine("x="+x); } } class b

{ public static void Main() { a t=new a(333); t.display(); } }

Download Source Code Example of Readonly keyword in C#

/*readonly The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. */ using System; public class ReadOnlyTest { class MyClass { public int x; public readonly int y = 25; // Initialize a readonly field public readonly int z; public MyClass() { z = 24; // Initialize a readonly instance field } public MyClass(int p1, int p2, int p3) { x = p1; y = p2; z = p3; } } public static void Main() { MyClass p1= new MyClass(11, 21, 32); // OK Console.WriteLine("p1: x={0}, y={1}, z={2}" , p1.x, p1.y, p1.z); MyClass p2 = new MyClass();

p2.x = 55; // OK Console.WriteLine("p2: x={0}, y={1}, z={2}" , p2.x, p2.y, p2.z); } } Download Source Code

Example of define Get and Set Using C#

/*Property :- It is just like method. Used to initials and access the private attribute of class get -->To get value set -->To set value */ using System; public class a { private string name; //Property public string ram { get { return name; } set { name = value; //value=keyword } } } public class MainClass { public static void Main() { a x=new a(); x.ram="santosh"; //set System.Console.WriteLine(x.ram); //get } } Download Source Code

Return More Then One Value C#

//out :- to return more then one value using System; public class MyClass { public static int disp(out char i,out char p) { i = 'b'; p = 'c'; return -1; } public static void Main() { char j='a',k='r'; // variable need not be initialized int h=(disp(out j,out k)); Console.WriteLine(j); Console.WriteLine(k); Console.WriteLine(h); } }

Download Source Code

Example of Interface in C#

/*Interface:- It is like an abstract class. it is use to support multiple inheritance it can not contain concrete method Abstract class Interface ============== =========== 1)It can contain 1)Not allowed concrete method 2)Access modifiers-private 2)Public 3)Multiple inheritance not 3)do also

*/ interface a { void display(); //it cant be public //By default it is abstract and public }

interface b { void display1(); } class c : a,b { public void display() { System.Console.WriteLine("Interface"); } public void display1() { System.Console.WriteLine("Interface one"); } } class d { public static void Main() { c t=new c(); t.display(); t.display1(); } }

Download Source Code

Create an array of object and Define Indexers in C#

/*To create array of object Indexers allow you to index a class or a struct instance in the same way as an array. Defining an indexer allows you to create classes that act like "virtual arrays." Instances of that class can be accessed using the [] array access operator. */ using System; class IndexerClass { private int [] myArray = new int[100]; public int this [int index] // Indexer declaration { get { return myArray[index];

} set { myArray[index] = value; } } } public class MainClass { public static void Main() { IndexerClass b = new IndexerClass(); // Call the indexer to initialize the elements #3 and #5. b[3] = 256; b[5] = 1024; for (int i=0; i<=10; i++) { Console.WriteLine("Element #{0} = {1}", i, b[i]); } } }

Download Source Code

Example Of Enumeration in C#

// enum :- Used to declare multiple constant using System; public class A { enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri}; public static void Main() { int x = (int) Days.Sun; int y = (int) Days.Fri; Console.WriteLine("Sun = {0}", x); Console.WriteLine("Fri = {0}", y); } } Download Source Code

Example of Delegate Declaration in C#

/*Delegates :- Function pointer. It conation reference of Function */ using System; // delegate declaration delegate void MyDelegate(); public class a { public void display() { Console.WriteLine("Hello."); } } public class b { static public void Main() { a x=new a(); // Map the delegate to the instance method MyDelegate d = new MyDelegate(x.display); d(); } } Download Source Code

Example Array in C#

/*Array:C# supports single-dimensional arrays, multidimensional arrays (rectangular arrays), and array-of-arrays (jagged arrays). To Declare:========== Single-dimensional arrays: int[] numbers; Multidimensional arrays: string[,] names; Array-of-arrays (jagged): byte[][] scores; Declaring them does not actually create the arrays.In C#,

arrays are objects and must be instantiated. The following examples show how to create arrays: Single-dimensional arrays: int[] numbers = new int[5]; Multidimensional arrays: string[,] names = new string[5,4]; Array-of-arrays (jagged): byte[][] scores = new byte[5][]; for (int x = 0; x < scores.Length; x++) { scores[x] = new byte[4]+x; } Initializing Arrays ============= Single-Dimensional Array ===================== int[] numbers = new int[5] {1, 2, 3, 4, 5}; string[] names = new string[3] {"Matt", "Joanne", "Robert"}; You can omit the size of the array, like this: int[] numbers = new int[] {1, 2, 3, 4, 5}; string[] names = new string[] {"Matt", "Joanne", "Robert"}; You can also omit the new operator if an initializer is provided, like this: int[] numbers = {1, 2, 3, 4, 5}; string[] names = {"Matt", "Joanne", "Robert"}; Multidimensional Array =================== int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = new string[2, 2] { {"Mike","Amy"}, {"Mary","Albert"} }; You can omit the size of the array, like this: int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = new string[,] { {"Mike","Amy"}, {"Mary","Albert"} }; You can also omit the new operator if an initializer is provided, like this: int[,] numbers = { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = { {"Mike", "Amy"}, {"Mary", "Albert"} }; Jagged Array (Array-of-Arrays) ======================== You can initialize jagged arrays like this example:

int[][] numbers = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} }; You can also omit the size of the first array, like this: int[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} }; -orint[][] numbers = { new int[] {2,3,4}, new int[] {5,6,7,8,9} }; using foreach:============= int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0}; foreach (int i in numbers) { System.Console.WriteLine(i); } */ using System; class DeclareArraysSample { public static void Main() { // Single-dimensional array int[] numbers = new int[5]; // Multidimensional array string[,] names = new string[5,4]; // Array-of-arrays (jagged array) byte[][] scores = new byte[5][]; // Create the jagged array for (int i = 0; i < scores.Length; i++) { scores[i] = new byte[i+3]; } // Print length of each row for (int i = 0; i < scores.Length; i++) { Console.WriteLine("Length of row {0} is {1}", i, scores[i].Length); } } }

Download Source Code

Example of Abstract class in C#

/*Abstract class class :- 1)Concreet class(We can create object of that) **method:- concreet method(method having body) 2)Abstract class(we can not create object, because it is too general ) **method :-1) abstract method(method without body) 2) concrete method it is used to inherit */ abstract class human { //Abstract methods public abstract void hair(); //Concrete method public void display() { System.Console.WriteLine("hello"); } } class boys : human { public override void hair() { System.Console.WriteLine("Small"); } } class girls : human { public override void hair() { System.Console.WriteLine("LONG"); } } class a { public static void Main() { boys b=new boys(); girls g=new girls(); b.hair(); g.hair(); b.display(); g.display();

} } Download Source Code

C# Interview Questions And Answers

Page 1
Ques: 1 what is partial class in .net 2.0 Ans: Single Class can be separated into multiple physical files with same logical name. Ans: Partial Class:-Using the partial keyword indicates that other parts of the class, struct, or interface can be defined within the namespace

Below is the example of a partial class. Listing 1: Entire class definition in one file (file1.cs) public class Node { public bool Delete() { } public bool Create() { } } Listing 2: Class split across multiple files (file1.cs) public partial class Node { public bool Delete() { } } (file2.cs) public partial class Node { public bool Create() { } }

Ques: 2 I want to delete an dll with a newer version, but nothing it throws an UnauthorizedAccessException! please help!!!

Assembly a = Assembly.LoadFile(source); Assembly b = Assembly.LoadFile(des Ans: a Ques: 3 Ans: Hi there, i have been programming for a few weeks now, i am still learning new things as i go on. i would like to understand a few more things about c# if anyone can answer my questions i would be more then appreciated. - What is the rule i must consider before placing a semi-colon? - What is the best data type to use to hold a value of 1200.0? and is there any other data types that could be used and why should i choose the other. - What is the defence between = and ==? And do i need to use both? - What is the defrence between a while and a do-while loop? - What is a class? And why is it so important to be used? Ques: 4 What is server code and client code in C#? Ans: Code which execute on client are called client side code Otherwise Server side code. Ans: Server code is run on server side and client code is run client side. Ans: Server side code will execute at server end all the business logic will execute at server end where as client side code will execute at client side at browser end. Ques: 5 Why we using in header file using system and more header file is in C# what is difference between and all header file ? Ques: 6 Give Real life examples of polymorphisms, encapsulation and inheritance? Ans: real lif example of inheritance is parent child relationship Ques: 7 What is partial class?what is its advantage. Ans: Partial Class: when a class need to be implemented at multiple locations with same class name then those classes need to be declared as "partial". Example:

public main() { class Test { ------------} class Test //error { ------------} } public main() { partial class Test { ------------} partial class Test //correct { ------------} } Ques: 8 What is the name of c#.net compiler? Ans: csc Ans: .cs Comliler Ans: Name of c# .net compiler is CSC. CSC stands foe C SHARP COMPILER. Ans: Just In time (JIT) Compiler....!! Ans: JIT Just In Time Compiler act as interface between IDE to OS after Common run time compilation is done Ques: 9 What is an object? Ans: Object:-Object is the basic run time entity. The object type is based on System.Object in the .NET Framework. You can assign values of any type to variables of type object. All data types, predefined and user-defined, inherit from the System.Object class. The object data type is the type to and from which objects are boxed. Exapmle:-

class a {} public static void Main() { a ob= new a();// create object ob of class a; } Ques: 10 What is a class? Ans: Class:Classes are declared using the keyword class. The declaration takes the form: [attributes] [modifiers] class identifier [:base-list] { class-body }[;] where: attributes (Optional) :-Additional declarative information. modifiers (Optional):The allowed modifiers are new, abstract, sealed, and the four access modifiers. identifier:The class name. base-list (Optional) :-A list that contains the one base class and any implemented interfaces, all separated by commas. class-body :-Declarations of the class members. Example:Public class a { // some members and parameter } Ques: 11 what abstraction,encapsulation,inheritance? Define with example. Ans: Abstraction:-Abstraction is the process of hiding the details and exposing only the essential features of a particular concept or object. Abstraction is another good feature of OOPS. Abstraction means to show only the necessary details to the client of the object Example:-A simple example is using a base class "Animal", with a virtual function "Walk". In the case two-legged versus four-legged animals, both of them walk, but the actual mechanics are different. The "Walk" method abstracts the actual mechanics behind the walking that each "Animal" does. 2nd example:-A class called Animal. It has properties like ears,colour, eyes but they are not defined. It has methods like Running(), Eating(), etc. but the method does not have any body, just the definition. Encapsulation:-Encapsulation is the term given to the process of hiding all the details of an object that do not contribute to its essential characteristics.its wrapping of data and members in a single unit.Encapsulation is a process of hiding all the internal details of an object from the outside world .

1:- Encapsulation is the ability to hide its data and methods from outside the world and only expose data and methods that are required . 2.Encapsulation gives us maintainability, flexibility and extensibility to our code. 3.Encapsulation provides a way to protect data from accidental corruption . 4.Encapsulation gives you the ability to validate the values before the object user change or obtain the value . 5.Encapsulation allows us to create a "black box" and protects an objects internal state from corruption by its clients. 6.Encapsulation is the technique or process of making the fields in a class private and providing access to the fields using public methods. Example:-cars and owners... all the functions of cars are encapsulated with the owners.. No one else can access it... Inheritance:-In object-oriented programming (OOP), Inheritance is a way to compartmentalize and reuse code by creating collections of attributes and behaviors called objects which can be based on previously created objects. In classical inheritance where objects are defined by classes. classes can inherit other classes. The new classes, known as Sub-classes (or derived classes), inherit attributes and behavior of the pre-existing classes, which are referred to as Super-classes. the process of deriving one class from parent class called . Example:-INHERITANCE MEANS A CHILD CLASS USE THE ALL THE ELEMENTS IN THE PARENTS CLASS. DAD | CHILED Seccond Example:Kingfisher jet ^ | Airplane ^ | Flying Things Ques: 12 What is mean "Death of Diamod"? Ans: Death Diamond:-In object-oriented programming languages with multiple inheritance and knowledge organization, the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B, or C? For example a class Button may inherit from both classes Rectangle (for appearance) and Clickable (for functionality/input handling), and classes Rectangle and Clickable both inherit from the Object class. Now if the equals method is called for a Button object and there is no such method in the Button class but there is an overridden equals method in both Rectangle and Clickable, which method should be eventually called? ihis is called "Death of Diamond". Ex: Class a

{ } class b: a {} class c: a {} class d:b,c {} It is called the "diamond problem" because of the example of the class inheritance in this situation. In this example, class A is at the top, both B and C separately inherit to A, and D inherits both...... Ques: 13 what is the main difference between delegate and an event in c#? Ans: Delegate:-A delegate is basically a reference to a method. A delegate can be passed like any other variable. This allows the method to be called anonymously, without calling the method directly. delegate declaration defines a reference type that can be used to encapsulate a method with a specific signature. A delegate instance encapsulates a static or an instance method. Delegates are roughly similar to function pointers in C++; however, delegates are type-safe and secure. The delegate declaration takes the form: [attributes] [modifiers] delegate result-type identifier ([formalparameters]) Event:-An event in one program can be made available to other programs that target the .NET runtime. An event is a member that enables an object or class to provide notifications. Clients can attach executable code for events by supplying event handlers. Events are declared using event-declarations: event-declaration: event-field-declaration event-property-declaration event-modifier: new public protected internal private static Example:public delegate void EventHandler(object sender, Event e); public class Button: Control { public event EventHandler Click; protected void OnClick(Event e) { if (Click != null) Click(this, e); } public void Reset() { Click = null; } }

Ques: 14 How to use Hash Table,ArrayList in c# ?Explain with example. Ans: ArrayList:-Arraylist is a collection of objects(may be of different types). Arraylist is very much similar to array but it can take values of different datatypes. If you want to find something in a arraylist you have to go through each value in arraylist, theres no faster way out.ArrayList's size can be changed dynamically. Items are added to the ArrayList with the Add() method. example:-HOW TO ADD DATA IN ARRAYLIST: using System.Collections; class Program { static void Main() { // // Create an ArrayList and add three elements. // ArrayList list = new ArrayList(); list.Add("One"); list.Add("Two"); list.Add("Three"); } } EXAMPLE-Adding one ArrayList to second one There are different ways to add one ArrayList to another, but the best way is using AddRange. Internally, AddRange uses the Array.Copy or CopyTo methods, which have better performance than some loops. === Program that uses Add and AddRange === using System; using System.Collections; class Program { static void Main() { // // Create an ArrayList with two values. // ArrayList list = new ArrayList(); list.Add(15); list.Add(17); // // Second ArrayList. // ArrayList list2 = new ArrayList(); list2.Add(110); list2.Add(113); // // Add second ArrayList to first. // list.AddRange(list2);

// // Display the values. // foreach (int i in list) { Console.WriteLine(i); } } } === Output of the program === 15 17 110 113 The ArrayList class provides the Count property, which is a virtual property. When you use Count, no counting is actually done; instead, a cached field value is returned HASH TABLE:-Hashtable is also collection which takes a key corresponding to each values. If you want to find something in a hashtable you dont have to go through each value in hashtable, instead search for key values and is faster.The Hashtable lets you quickly get an object out of the collection by using it's key. The Hashtable object contains items in key/value pairs. The keys are used as indexes. We can search value by using their corresponding key. The data type of Hashtable is object and the default size of a Hashtable is 16. Items are added to the Hashtable with the ADD()method. Example-How to add data in hash table:-Add method of Hashtable is used to add items to the hashtable. The method has index and value parameters. The following code adds three items to hashtable. hshTable .Add("A1", hshTable .Add("A2", hshTable .Add("A3", "Kamal"); "Aditya"); "Ashish");

Retrieving an Item Value from Hashtable The following code returns the value of "Author1" key: string name = hshTable["A1"].ToString(); Removing Items from a Hashtable The Remove method removes an item from a Hashtable. The following code removes item with index "A1" from the hashtable: hshTable.Remove("A1");

Looking through all Items of a Hashtable

The following code loops through all items of a hashtable and reads the values. // Loop through all items of a Hashtable IDictionaryEnumerator en = hshTable.GetEnumerator(); while (en.MoveNext()) { string str = en.Value.ToString(); } Ques: 15 What is the difference between shadow and override ? Ans: Difference between shadow and override:Shadowing hide the inherrited method using new keyword and CLR choose the target mthod between the parent and child to call using the object's runtime type.Overriding hide the inherrited method using override keyword and the parent should be virtual. overrding always choose the object's compile-time type. Differences:1-PorPose:SHADOW-Protecting against a subsequent base class modification introducing a member you have already defined in your derived class. OVERRIDE-Achieving polymorphism by defining a different implementation of a procedure or property with the same calling sequence 2-Redefined element:SHADOW:-Any declared element type. OVERRIDE:-Only a procedure (Function or Sub) or property 3-Accessibility:SHADOW:-Any accessibility OVERRIDE:-Cannot expand the accessibility of overridden element (for example cannot override Protected with Public) 4-Readability and writability SHADOW:-Any combination OVERRIDE:-Cannot change readability or writability of overridden property 5-Keyword usage SHADOW:-Shadows recommended in derived class; Shadows assumed if neither Shadows nor Overrides specified. OVERRIDE:-Overridable required in base class; Overrides required in derived class Ques: 16 What is the top .NET class that everything is derived from? Ans: System.Object Ques: 17 When we can inherit a protected class-level variable? Ans: Classes in the same namespace. Ques: 18 Does C# support multiple inheritance? Ans: No directly,but we can use interface for multiple inheritence Ans: No directly,but we can use interface for multiple inheritence Ques: 19 How do you inherit from a class in C#? Ans: Place a colon and then the name of the base class. exmple:-

class a {} class b: a //inherit class a {} Ques: 20 What is an abstract class? Ans: Abstract class:-Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Abstract classes have the following features: 1-An abstract class cannot be instantiated. 2-An abstract class may contain abstract methods and accessors. 3-It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited. 4-A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors. Abstract class have complete and non complete member and methods. Example:- abstract class a { int a; public abstract void print(); }

C# Interview Questions And Answers

Page 1
Ques: 1 Explain Exception handling Ans: Exception Handling:-# provides built-in support for handling anomalous situations, known as exceptions, which may occur during the execution of your program. These exceptions are handled by code that is outside the normal flow of control. The try, throw, catch, and finally keywords implement exception handling. Throw:-The throw statement is used to signal the occurrence of an anomalous situation (exception) during the program execution. The throw statement takes the form: throw [expression]; where: expression :The exception object. This is omitted when re-throwing the current exception object in a catch clause. Try:The try-block contains the guarded code block that may cause the exception. The block is executed until an exception is thrown or it is completed successfully. For example, the following attempt to cast a null object raises the NullReferenceException exception: object o2 = null; try { int i2 = (int) o2;

// Error

} Catch:The catch clause can be used without arguments, in which case it catches any type of exception, and referred to as the general catch clause. It can also take an object argument derived from System.Exception, in which case it handles a specific exception. For example: catch (InvalidCastException e) { } Finally:finally is used to guarantee a statement block of code executes regardless of how the preceding try block is exited. The finally block is useful for cleaning up any resources allocated in the try block. Control is always passed to the finally block regardless of how the try block exits. The try-finally statement takes the form: try try-block finally finally-block where: try-block Contains the code segment expected to raise the exception. finally-block Contains the exception handler and the cleanup code. Ques: 2 Explain exception handling in C#? Ques: 3 What is Event? Ans: Event:-The Event model in C# finds its roots in the event programming model that is popular in asynchronous programming. The basic foundation behind this programming model is the idea of "publisher and subscribers." Example:using System; using System.IO; namespace EventExample { public class MyClass { public delegate void LHandler(string message); // Define an Event based on the above Delegate public event LHandler Log; // Instead of having the Process() function take a delegate // as a parameter, we've declared a Log event. Call the Event, public void Process() { OnLog("Process() begin"); OnLog("Process() end"); } protected void OnLog(string message)

{ if (Log != null) { Log(message); } } } // The FLog class merely encapsulates the file I/O public class FLog { FileStream fileStream; StreamWriter streamWriter; // Constructor public FLog(string filename) { fileStream = new FileStream(filename, FileMode.Create); streamWriter = new StreamWriter(fileStream); } // Member Function which is used in the Delegate public void Logger(string s) { streamWriter.WriteLine(s); } public void Close() { streamWriter.Close(); fileStream.Close(); } } public class TestApplication { static void Logger(string s) { Console.WriteLine(s); } static void Main(string[] args) { FLog fl = new FLog("process.log"); MyClass myClass = new MyClass(); // Subscribe the Functions Logger and fl.Logger myClass.Log += new MyClass.LHandler(Logger); myClass.Log += new MyClass.LHandler(fl.Logger); // The Event will now be triggered in the Process() Method myClass.Process(); fl.Close(); } } }

Compile an test: # csc EventExample.cs # EventExapmle.exe Process() begin Process() end # cat process.log Process() begin Process() end

An event is a placeholder for code that is executed when the event is triggered, or fired. Events are fired by a user action, program code, or by the system.

The following important conventions are used with events: * Event Handlers in the .NET Framework return void and take two parameters. * The first paramter is the source of the event; that is the publishing object. * The second parameter is an object derived from EventArgs. * Events are properties of the class publishing the event. * The keyword event controls how the event property is accessed by the subscribing classes. Ques: 4 What is indexer? Ans: Indexer:* Indexer Concept is object act as an array. * Indexer an object to be indexed in the same way as an array. * Indexer modifier can be private, public, protected or internal. * The return type can be any valid C# types. * Indexers in C# must have at least one parameter. Else the compiler will generate a compilation error. Signature:his [Parameter] { get { // Get codes goes here

} set { // Set codes goes here } } ................................................. Exapmle:using System; using System.Collections.Generic; using System.Text;

namespace Indexers { class PClass { private string[] range = new string[5]; public string this[int indexrange] { get { return range[indexrange]; } set { range[indexrange] = value; } } }

/* The Above Class just act as array declaration using this pointer */

class cclass { public static void Main() { PClass obj = new PClass();

obj[0] = "ONE"; obj[1] = "TWO"; obj[2] = "THREE"; obj[3] = "FOUR "; obj[4] = "FIVE"; Console.WriteLine("WELCOME TO C# CORNER HOME PAGE\n"); Console.WriteLine("\n");

Console.WriteLine("{0}\n,{1}\n,{2}\n,{3}\n,{4}\n", obj[0], obj[1], obj[2], obj[3], obj[4]); Console.WriteLine("\n"); Console.WriteLine("ALS.Senthur Ganesh Ram Kumar\n"); Console.WriteLine("\n"); Console.ReadLine(); } } } Ques: 5 What is Methods? Ans: Method:-Method is object-oriented item of any language. All C# programs are constructed from a number of classes and almost all the classes will contain

methods. A class when instantiated is called an object. Object-oriented concepts of programming say that the data members of each object represent its state and methods represent the object behavior. Method Signature:Each method is declared as follows: Access modifier Return-type methodname ( Parameterslist );

Example:- public string printpro(string s,int y); Ans: Method:-Method is object-oriented item of any language. All C# programs are constructed from a number of classes and almost all the classes will contain methods. A class when instantiated is called an object. Object-oriented concepts of programming say that the data members of each object represent its state and methods represent the object behavior. Method Signature:Each method is declared as follows: Access modifier Return-type methodname ( Parameterslist );

Example:- public string printpro(string s,int y); Ques: 6 What is Static classes? Ans: Static Class:-These are simply declared using the static modifier. They cannot be derived from or instantiated, and they have no constructors . Their members must all be static. Example:using System; public static class staticexample { public static void Foo() { Console.WriteLine ("Hello"); } } // Uncommenting this creates a compile-time error, // as static classes can't be derived from // public class DerivationAttempt :staticexample{} class Test { static void Main() { staticexample.Foo(); } } Ques: 7 What is Aliases? Ans: Aliases:-C# 2.0 introduces the concept of an "alias". This allows you to effectively name an assembly reference when you compile the code, and use that name to disambiguate between names. As well as disambiguating between

identical namespace-qualified names, aliases allow you to disambiguate between names which have been declared within an already used namespace and names which belong to the "root" namespace. This is achieved with the predefined alias of global. Example:using System; namespace Foo.Bar { public class Baz { public static void SayHiLib() { Console.WriteLine ("Hello Lib"); } } } Baz.cs: using System; namespace Foo.Bar { public class Baz { public static void SayHiNested() { Console.WriteLine ("Hello Nested"); } } } class Baz { public static void SayHiBaz() { Console.WriteLine ("Hello Baz"); } } Test.cs: extern alias X; namespace Foo.Bar { class Test { public static void Main() { Baz.SayHiNested(); global::Baz.SayHiBaz(); X::Foo.Bar.Baz.SayHiLib();

} } } Compile: csc /target:library Lib.cs csc /r:X=lib.dll Baz.cs Test.cs Ques: 8 What is Partial types? Ans: Partial Type:-C# 2.0 introduces the concept of a partial type declaration. This is quite simply a single type which spans multiple files, where each file declares the same type using the partial modifier. The files may refer to members declared within one another without problem (just as forward references within C# is already not a problem). Example:1st Part-partial class Test { string name; static void Main() { Test t = new Test("C# 2.0"); t.SayHello(); } } 2ND PART:using System; partial class Test { Test(string name) { this.name = name; } void SayHello() { Console.WriteLine ("Hi there. My name is {0}.", name); } Compile with: csc Test1.cs Test2.cs Results: Hi there. My name is C# 2.0. Ques: 9 What is Method Overloading ? Ans: Method Overloading:-A method is considered to be an overloaded method, if it has two or more signatures for the same method name. These methods will

contain different parameters but the same return types.It become within the class. A simple example for an overloaded methods are: Public void sum(int a, params int[] varParam); Public void sum(int a); Ques: 10 Wat's Property? Ans: PROPERTY:-Properties provide the opportunity to protect a field in a class by reading and writing to it through the property it is a special method that can return a current object?s state or set it. Simple syntax of properties can see in the following example: public { get set } public { get int Old {return m_old;} {m_old = value;} string Name {return m_name;}

Example:public class prop { private int age; public int humanAge { get //get accessor method { return age; } set //set accessor method { age = value; } } } So when in main program(C#) user wants to use these set and get method to set and get person age. They will use it as Perop boyAge = new Perop(); //create instance of object boyAge. humanAge = 10; // set the age of boy by using setter method of object int bAge = boyAge. humanAge;// get the age of boy by // using getter method of object Console.WriteLine(" Boy age is {0}"+ bAge ); Class Perop is property holder class. In which humanAge is property implementation.

value : In set method value variable is internal c# variable. User no needs to define it explicitly. Ques: 11 Wat's feature of delegate? Ans: Features of delegates: * A delegate represents a class. * A delegate is type-safe. * We can use delegates both for static and instance methods * We can combine multiple delegates into a single delegate. * Delegates are often used in event-based programming, such as publish/subscribe. * We can use delegates in asynchronous-style programming. * We can define delegates inside or outside of classes. Ques: 12 What's Delegate? Ans: Delegate:- delegate is a type-safe object that can point to another method (or possibly multiple methods) in the application, which can be invoked at later time. when you want to create a delegate in C# you make use of delegate keyword. A delegate type maintains three important pices of information : 1. The name of the method on which it make calls. 2. Any argument (if any) of this method. 3. The return value (if any) of this method. signature of delegate:Access modifier delegate returntype delegatename (passing value must be same as a function ); public delegate int DelegateName(int x, int y); Example:namespace MyFirstDelegate { public delegate int MyDelegate(int x, int y); public class MyClass { public static int Add(int x, int y) { return x + y; } public static int Mul(int x, int y)

{ return x * y; } } class Program { static void Main(string[] args) { MyDelegate del1 = new MyDelegate(MyClass.Add); int addResult = del1(5, 5); Console.WriteLine("5 + 5 = {0}\n", addResult); MyDelegate del2 = new MyDelegate(MyClass.Mul); int multiplyResult = del2(5, 5); Console.WriteLine("5 X 5 = {0}", multiplyResult); Console.ReadLine(); } } } Ques: 13 What's REF Keyword? Ans: REF:-A reference type and sending a parameter by reference are two different things. If you send a reference type to a method (passed by value), then the reference is passed by value. Since you are sending a reference, you can still access the same object outside of the method using another variable set to the same reference. Now, if you pass that reference by ref, you can modify the value of that parameter so that it holds a new reference to a new object. When you pass it by value, you can't do that. Example:Using System; class Color { public Color() { this.red = 255; this.green = 0;

this.blue = 125; } protected int red; protected int green; protected int blue; public void Getscol(ref int red, ref int green, ref int blue) { red = this.red; green = this.green; blue = this.blue; } } class RefTest1App { public static void Main() { Color color = new Color(); int red; int green; int blue; color.Getscol(ref red, ref green, ref blue); Console.WriteLine("red = {0}, green = {1}, blue = {2}", red, green, blue); } } Ques: 14 What's OUT Keyword? Ans: OUT:-out keyword is used for passing a variable for output purpose. It has same concept as ref keyword, but passing a ref parameter needs variable to be initialized while out parameter is passed without initialized. It is useful when we want to return more than one value from the method.

Example of out keyword: class Test { public static void Main() { int a; fun(out a); Console.WriteLine("The value of a is " + a); } public static void fun(out int i) { i=4; //must assigned value. } } The program will result : The value of a is 4 Ques: 15

what's Param? Ans: Params:-The params keyword is used to describe methods that can receive any number of parameters of the specified type, and it results in extra allocations and reduced performance but improves the flexibility of the calling patterns. The main use of the params keyword is to give the ability to create functions that take a variable number of arguments. Example:Public int sumnumber(params int[] list) { int sum = 0; foreach (int i in list) sum += i; return sum; } Public static void Main() { int ans1 = sumnumber(1); int ans2 = int ans3 = int ans4 = } OUTPUT:1 55 55 0 Ques: 16 Is there an easy way to get help about an object's member Ans: Absolutely. Visual C#'s context-sensitive Help extends to code as well as to visual objects. To get help on a member, write a code statement that includes the member (it doesn't have to be a complete statement), position the cursor within the member text, and press F1. For instance, to get help on the int data type, you could type int, position the cursor within the word int, and press F1. Ques: 17 Is it possible for objects that don't have an interface to support events? Ans: Yes. To use the events of such an object, however, the object variable must be dimensioned a special way or the events aren't available. Ques: 18 Is it possible to create custom events for an object sumnumber(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); sumnumber(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); sumnumber()

Ans: Yes, you can create custom events for your own objects and you can also create them for existing objects. Creating custom events, Ques: 19 Whats an interface class? Ans: Its an abstract class with public abstract methods all of which must be implemented in the inherited classes. Ques: 20 Can you override private virtual methods? Ans: No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.

C# Interview Questions And Answers

Page 1
Questions Show Answers Total Post Your Posts Answers 15 Post Your Answers Post Your Answers Last Post

Does C# support multiple-inheritance? Show 1.No Answers 2.Yes What is MSIL? Show 1.Multi Socket Interface Library 2.Microsoft Intermediate Language Answers 3.Microsoft Interface Language 4.Microsoft Integer Long Whict is true for C#? 1.C# supports interfaces. 2.C# also provides support for Show structs. Answers 3.C# provides component-oriented features 4.All 5.None An assembly is> 1.A collection of files that appear to the programmer to be a single DLL or Show EXE. Answers 2.properties of c# 3.events Of c# 4.declarative syntax of Java Which Of follwing is currect syntax? 1.class R4R Show { static void Main( ) Answers { System.Console.WriteLine("R4R"); }

jitendra kumar mpec

praveen

Post Your Answers

RAJ

Post Your Answers

jyoti

Post Your Answers

Raja

} 2.class R4R { static void Main( ) { System.out.WriteLine("R4R"); } } 3.class R4R { static void Main( ) { System.print.WriteLine("R4R"); } } 4.class R4R { static void Main( ) { System.Console.out("R4R"); } } 5.class R4R { static void Main( ) { System.Console.out("R4R"); } } What will output of following class R4R { static void Main( ) { /* System.Console.WriteLine("R4R"); */ } } 1.No any output. 2.Compile time error. 3.Runtime erro 4 .None of above. What will output of following ? using System.Console; class R4R { static void Main( )

Show Answers

Post Your Answers

Navjyoti Sharma

Show Answers

Post Your Answers

Vinay Tyagi

{ WriteLine("R4R"); } } 1. 2. 3. 4. error CS0138 R4R No any output None

Which of the follwing is true? 1.byte-->> 1(siz)-->>Byte(as int.net)->> Unsigned (values 0-255). 2.char-->> 2-->> Char -->>Unicode-->> Show characters. 3.bool -->>1 -->>Boolean -->>true or Answers false. 4.sbyte-->> 1 SByte-->> Signed ->>(values -128 to 127). 5.short-->> 2-->> Int16-->> Signed -->> short-->> values -32,768 to 32,767 class R4R { static void Main( ) { short x; int y = 500; x = y; Show System.Console.WriteLine("Output:{0}", Answers x); } } 1.error 2.Output:500 3.Outpu:{500} 4.None class R4R { static void Main( ) { short s = 7; System.Console.WriteLine("Initialized: {0}",s); Show s = 5; System.Console.WriteLine("After Answers assignment: {0}",s); } } 1. error 2. 2 Initialized:5 3. After assignment:7 4. both 2,3 5. None

Post Your Answers

Vishnu

Post Your Answers

sarika mann

Post Your Answers

Vishnu

class R4R { static void Main( ) { short s; System.Console.WriteLine("Initialized: {0}",s); s = 5; Show System.Console.WriteLine("After Answers assignment: {0}",s); } } 1. error 2. 2 Initialized:5 3. After assignment:7 4. both 2,3 5. None Which of following is correct: 1. enum Day { Sunday= 01, Monday= 02, Tuesday= 03, Wednesday=04, Thursday= 05, Friday= 06, Saturday=07 } 2. Day enum { Sunday= 01, Monday= 02, Tuesday= 03, Wednesday=04, Thursday= 05, Friday= 06, Saturday=07 } 3. Day { Sunday= 01, Monday= 02, Tuesday= 03, Wednesday=04, Thursday= 05, Friday= 06, Saturday=07 } 4.enumeration Day { Sunday= 01, Monday= 02,

Post Your Answers

sarika mann

Show Answers

Post Your Answers

11.03.10 Vikas

Tuesday= 03, Wednesday=04, Thursday= 05, Friday= 06, Saturday=07 } What is output of following : class R4R { enum Day { Sunday= 01, Monday= 02, Tuesday= 03, Wednesday=04, Thursday= 05, Friday= 06, Saturday=07 } Show static void Main( ) { Answers System.Console.WriteLine("First of Weak Day: {0}", (int) Day.Sunday); System.Console.WriteLine("Last of Weak Day: {0}", (int) Day.Saturday); } } 1. First of Weak Day:01 2. Last of Weak Day:07 3. 1,2 4. error 5. None Which of the following is true for string r4r = "R4R"; 1.r4r is an object which store string R4R. 2.string is keyword in C#. 3.This syntax is wrong string is not any keyword in c#. 4.string used to store set of characters into any string type object. What is output of following : class R4R static void Main( ) { Int string=0; System.Console.WriteLine("Outpt: {0}",string++); } }

Post Your Answers

Vishnu

Show Answers

Post Your Answers

11.03.10 Rahul

Show Answers

Post Your Answers

Vinay Tyagi

1.Outpt:0 2.Outpt:1 3.1,2 4.error 5.None How many statements are into following code? int x; x = 23;int y = x; 1.1 2.2 3.3 4.4 5.5 Choose correct one 1.int x; 2 x = 23; 3 int y = x; 4 int string=10;

Show Answers

Post Your Answers

11.03.10 Rajesh Kumar

1.1,2,3,4 2.1,2,3 3.1,3 4. None 5. All using System; class R4R { static void Main( ) { int x = 10; int y; y = x++; Console.WriteLine("After postfix: {0}, {1}", x, Show y); x = 20; Answers y = ++x; Console.WriteLine("After prefix: {0}, {1}", x, valueTwo); } } 1.After postfix: 10, 10 2.After prefix: 20, 20 3 both 4 none using System; class R4R { static void Main( ) {

Show Answers

Post Your Answers

Vishnu

Post Your Answers

11.03.10 Rahul

Show Answers

Post Your Answers

ajit dubey

int x = 10; int y; y = x++; Console.WriteLine("After postfix: {0}, {1}", x, y); x = 20; y = ++x; Console.WriteLine("After prefix: {0}, {1}", x, valueTwo); } } 1.After postfix: 11, 10 2.After prefix: 21, 21 3 both 4 none using System; class R4R { static void Main( ) { int x = 10; int y; y = x++; int xy = x > y ? x : y; Console.WriteLine("output: {0}, {1},{2}", x,y,xy); } } 1. output: 10, 10,10 2. output: 11, 10,10 3. output: 11,10,11 4 none

Show Answers

Post Your Answers

ajit dubey

C# Interview Questions And Answers


General Questions Q1: Does C# support multiple-inheritance? Ans: No. Q2: Who is a protected class-level variable available to? Ans: It is available to any sub-class (a class inheriting this class). Q3: Are private class-level variables inherited? Ans: Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited.

Q4: Describe the accessibility modifier protected internal. Ans: It is available to classes that are within the same assembly and derived from the specified base class. Q5: Whats the top .NET class that everything is derived from? Ans: System.Object. Q6: What does the term immutable mean? Ans: The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory. Q7: Whats the difference between System.String and System.Text.StringBuilder classes? Ans: System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed. Q8: Whats the advantage of using System.Text.StringBuilder over System.String? Ans: StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created. Q9: Can you store multiple data types in System.Array? Ans: No. Q10: Whats the difference between the System.Array.CopyTo() and System.Array.Clone()? Ans: The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object. Q11: How can you sort the elements of the array in descending order? Ans: By calling Sort() and then Reverse() methods. Q12: Whats the .NET collection class that allows an element to be accessed using a unique key? Ans: HashTable. Q13: What class is underneath the SortedList class? Ans: A sorted HashTable. Q14: Will the finally block get executed if an exception has not occurred? Ans: Yes. Q15: Whats the C# syntax to catch any possible exception? Ans: A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}. Q16: Can multiple catch blocks be executed for a single try statement? Ans: No. Once the proper catch block processed, control is transferred to the finally block (if there are any).

Q17: Explain the three services model commonly know as a three-tier application. Ans: Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources). Class Questions Q18: What is the syntax to inherit from a class in C#? Ans: Place a colon and then the name of the base class. Example: class MyNewClass : MyBaseClass Q19: Can you prevent your class from being inherited by another class? Ans: Yes. The keyword sealed will prevent the class from being inherited. Q20: Can you allow a class to be inherited, but prevent the method from being overridden? Ans: Yes. Just leave the class public and make the method sealed. Q21: Whats an abstract class? Ans: A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation. Q22: When do you absolutely have to declare a class as abstract? Ans: 1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden. 2. When at least one of the methods in the class is abstract. Q23: What is an interface class? Ans: Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. Q24: Why cant you specify the accessibility modifier for methods inside the interface? Ans: They all must be public, and are therefore public by default. Q25: Can you inherit multiple interfaces? Ans: Yes. .NET does support multiple interfaces. Q26: What happens if you inherit multiple interfaces and they have conflicting method names? Ans: Its up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares youre okay. Q27: Whats the difference between an interface and abstract class? Ans: In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers.

Q28: What is the difference between a Struct and a Class? Ans: Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that structs cannot inherit. Method and Property Questions Q29: Whats the implicit name of the parameter that gets passed into the set method/property of a class? Ans: Value. The data type of the value parameter is defined by whatever data type the property is declared as. Q30: What does the keyword virtual declare for a method or property? Ans: The method or property can be overridden. Q31: How is method overriding different from method overloading? Ans: When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same name within the class. Q32: Can you declare an override method to be static if the original method is not static? Ans: No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to keyword override). Q33: What are the different ways a method can be overloaded? Ans: Different parameter data types, different number of parameters, different order of parameters. Q34: If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor? Ans: Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class. Events and Delegates Q35: Whats a delegate? Ans: A delegate object encapsulates a reference to a method. Q36: Whats a multicast delegate? Ans: A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called. XML Documentation Questions Q37: Is XML case-sensitive? Ans: Yes. Q38: Whats the difference between // comments, /* */ comments and /// comments? Ans: Single-line comments, multi-line comments, and XML documentation comments.

Q39: How do you generate documentation from the C# file commented properly with a command-line compiler? Ans: Compile it with the /doc switch. Debugging and Testing Questions Q40: What debugging tools come with the .NET SDK? Ans: 1. CorDBG command-line debugger. To use CorDbg, you must compile the original C# file using the /debug switch. 2. DbgCLR graphic debugger. Visual Studio .NET uses the DbgCLR. Q41: What does assert() method do? Ans: In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true. Q42: Whats the difference between the Debug class and Trace class? Ans: Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds. Q43: Why are there five tracing levels in System.Diagnostics.TraceSwitcher? Ans: The tracing dumps can be quite verbose. For applications that are constantly running you run the risk of overloading the machine and the hard drive. Five levels range from None to Verbose, allowing you to fine-tune the tracing activities. Q44: Where is the output of TextWriterTraceListener redirected? Ans: To the Console or a text file depending on the parameter passed to the constructor. Q45: How do you debug an ASP.NET Web application? Ans: Attach the aspnet_wp.exe process to the DbgClr debugger. Q46: What are three test cases you should go through in unit testing? Ans: 1. Positive test cases (correct data, correct output). 2. Negative test cases (broken or missing data, proper handling). 3. Exception test cases (exceptions are thrown and caught properly). Q47: Can you change the value of a variable while debugging a C# application? Ans: Yes. If you are debugging via Visual Studio.NET, just go to Immediate window. ADO.NET and Database Questions Q48: What is the role of the DataReader class in ADO.NET connections? Ans: It returns a read-only, forward-only rowset from the data source. A DataReader provides fast access when a forward-only sequential read is needed. Q49: What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? Ans: SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a .NET layer on top of the OLE layer, so its not as fastest and efficient as SqlServer.NET.

Q50: What is the wildcard character in SQL? Ans: Lets say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve La%. Q51: Explain ACID rule of thumb for transactions. Ans: A transaction must be: 1. Atomic - it is one unit of work and does not dependent on previous and following transactions. 2. Consistent - data is either committed or roll back, no in-between case where something has been updated and something hasnt. 3. Isolated - no transaction sees the intermediate results of the current transaction). 4. Durable - the values persist if the data had been committed even if the system crashes right after. Q52: What connections does Microsoft SQL Server support? Ans: Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password). Q53: Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted? Ans: Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction. Q54: What does the Initial Catalog parameter define in the connection string? Ans: The database name to connect to. Q55: What does the Dispose method do with the connection object? Ans: Deletes it from the memory. To Do: answer better. The current answer is not entirely correct. Q56: What is a pre-requisite for connection pooling? Ans: Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings. The connection string must be identical. Assembly Questions Q57: How is the DLL Hell problem solved in .NET? Ans: Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly. Q58: What are the ways to deploy an assembly? Ans: An MSI installer, a CAB archive, and XCOPY command. Q59: What is a satellite assembly? Ans: When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.

Q60: What namespaces are necessary to create a localized application? Ans: System.Globalization and System.Resources. Q61: What is the smallest unit of execution in .NET? Ans: an Assembly. Q62: When should you call the garbage collector in .NET? Ans: As a good rule, you should not call the garbage collector. However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. However, this is usually not a good practice. Q63: How do you convert a value-type to a reference-type? Ans: Use Boxing. Q64: What happens in memory when you Box and Unbox a value-type? Ans: Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack.

Potrebbero piacerti anche