https://github.com/kansiris/c-sharp-c-interview-question
List of top 500 C# csharp Interview Questions & Answers....Coding exercise questions are coming soon!!
https://github.com/kansiris/c-sharp-c-interview-question
interview-practice interview-questions namespace-sampleprogram programming-languages
Last synced: over 1 year ago
JSON representation
List of top 500 C# csharp Interview Questions & Answers....Coding exercise questions are coming soon!!
- Host: GitHub
- URL: https://github.com/kansiris/c-sharp-c-interview-question
- Owner: kansiris
- Created: 2019-07-07T01:41:15.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2021-10-31T13:39:51.000Z (over 4 years ago)
- Last Synced: 2025-01-06T19:43:00.123Z (over 1 year ago)
- Topics: interview-practice, interview-questions, namespace-sampleprogram, programming-languages
- Homepage:
- Size: 405 KB
- Stars: 155
- Watchers: 5
- Forks: 39
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# CSHARP C# Interview Questions & Answers
> Click :star:if you like the project. Pull Request are highly appreciated. Follow me [@kansiris87](https://twitter.com/kansiris87) for technical updates.
### Table of Contents
| No. | Questions |
|---- | ---------|
|1 | [What is Computer programming? ](# )|
|2 | [How programming work? ](# )|
|3 | [What is debugging? ](# )|
|4 | [Name different types errors which can occur during the execution of a program? ](# )|
|5 | [When a syntax error occurs? ](# )|
|6 | [When a runtime error occurs? ](# )|
|7 | [When a logical error occurs? ](# )|
|8 | [What is flowchart? ](# )|
|9 | [What is an algorithm? ](# )|
|10 | [What do you understand by the term 'Maintain and update the Program'? ](# )|
|11 | [What are variables? ](# )|
|12 | [What are reserved words? ](# )|
|13 | [What are Loop? ](# )|
|14 | [What is the use of FOR…NEXT Loop? ](# )|
|15 | [What is the use of WHILE…WEND Loop? ](# )|
|16 | [What is the use of Nested Loop? ](# )|
|17 | [What is Documentation? ](# )|
|18 | [What is the working of a compiler? ](# )|
|19 | [What do we call the binary form of a target language? ](# )|
|10 | [What are constants? ](# )|
|21 | [Define Numeric constants. ](# )|
|22 | [Define String constants. ](# )|
|23 | [Define Operators. ](# )|
|24 | [What is an Array? ](# )|
|25 | [What is subroutine? ](# )|
|26 | [What is the purpose of arithmetic operators? ](# )|
|27 | [What is the purpose of relational operators? ](# )|
|28 | [Define Low-level programming language. ](# )|
|29 | [Define High-Level programming language. ](# )|
|30 | [What is Machine code? ](# )|
|31 | [List some programming languages. ](# )|
|32 | [What is reliability? ](# )|
|3503 | [What is modeling language? ](# )|
|34 | [Name some modeling languages? ](# )|
|35 | [What is software testing? ](# )|
|36 | [What is Beta version? ](# )|
|37 | [What is the working of logical operators? ](# )|
|38 | [What is the purpose of assignment operator? ](# )|
|39 | [What is analyzing a program? ](# )|
|40 | [What is the working on an algorithm? ](# )|
|41 | [How is the division by zero defined? ](# )|
|42 | [What is the meaning of implementation of a program? ](# )|
|43 | [What are numeric variables? ](# )|
|44 | [What are string variables? ](# )|
|45 | [What are commands? ](# )|
|46 | [What are statements? ](# )|
|47 | [What is the execution of a program? ](# )|
|48 | [Define variable and constant. ](# )|
|49 | [What is a data type? How many types of data types are there in .NET ? ](# )|
|50 | [Mention the two major categories that distinctly classify the variables of C# programs. ](# )|
|51 | [Which statement is used to replace multiple if-else statements in code. ](# )|
|52 | [What is the syntax to declare a namespace in .NET? ](# )|
|53 | [Differentiate between the while and for loop in C#. ](# )|
|54 | [What is an identifier? ](# )|
|55 | [What does a break statement do in the switch statement? ](# )|
|56 | [Explain keywords with example. ](# )|
|57 | [Briefly explain the characteristics of value-type variables that are supported in the C# programming language. ](# )|
|58 | [What is a parameter? Explain the new types of parameters introduced in C# 4.0. ](# )|
|59 | [Briefly explain the characteristics of reference-type variables that are supported in the C# programming language. ](# )|
|60 | [What are the different types of literals? ](# )|
|61 | [What is the main difference between sub-procedure and function? ](# )|
|62 | [Differentiate between Boxing and Unboxing. ](# )|
|63 | [What is C#? ](# )|
|64 | [What is an Object? ](# )|
|65 | [What is the difference between a struct and a class in C#? ](# )|
|66 | [What is the difference between Interface and Abstract Class? ](# )|
|67 | [What is enum in C#? ](# )|
|68 | [What is the difference between “continue” and “break” statements in C#? ](# )|
|69 | [What is the difference between constant and readonly in c#? ](# )|
|70 | [What is the difference between ref and out keywords? ](# )|
|71 | [Can “this” be used within a static method? ](# )|
|72 | [Define Property in C# .net? ](# )|
|73 | [What is extension method in c# and how to use them? ](# )|
|74 | [What is the difference between string and StringBuilder in c#? ](# )|
|75 | [What are delegates in C# and uses of delegates? ](# )|
|76 | [What is sealed class in c#? ](# )|
|77 | [ What are partial classes? ](# )|
|78 | [ What is IEnumerable<> in c#? ](# )|
|79 | [ What is difference between late binding and early binding in c#? ](# )|
|80 | [What are the differences between IEnumerable and IQueryable? ](# )|
|81 | [What happens if the inherited interfaces have conflicting method names? ](# )|
|82 | [What are the Arrays in C#.Net? ](# )|
|83 | [What is the Constructor Chaining in C#? ](# )|
|84 | [What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? ](# )|
|85 | [Can Multiple Catch Blocks executed in c#? ](# )|
|86 | [Difference between Throw Exception and Throw Clause. ](# )|
|87 | [What is Indexer in C# .Net? ](# )|
|88 | [What is multicast delegate in c#? ](# )|
|89 | [Difference between Equality Operator (==) and Equals() Method in C#. ](# )|
|90 | [Difference between “is” and “as” operator in C#. ](# )|
|91 | [How to use Nullable<> Types in .Net? ](# )|
|92 | [Different Ways of Method can be overloaded. ](# )|
|93 | [What is an Object Pool in .Net? ](# )|
|94 | [What are generics in c#.net? ](# )|
|95 | [Describe the accessibility modifiers in c#.Net ](# )|
|96 | [What is Virtual Method in C#? ](# )|
|97 | [What is the Difference between Array and ArrayList in C#.Net? ](# )|
|98 | [What you understand by Value types and Reference types in C#.Net? ](# )|
|99 | [What is Serialization? ](# )|
|100 | [What is the use of using statement in C#? ](# )|
|101 | [What is jagged array in C#.Net? ](# )|
|102 | [What is Multithreading with .NET? ](# )|
|103 | [Explain Anonymous type in C#? ](# )|
|104 | [Explain Hashtable in C#? ](# )|
|105 | [What is LINQ in C#? ](# )|
|106 | [What is File Handling in C#.Net? ](# )|
|107 | [What is Reflection in C#.Net? ](# )|
|108 | [What is Expression Trees In C#? ](# )|
|109 | [Differences between Object, Var and Dynamic type? ](# )|
|110 | [What are OOPS Concepts? ](# )|
|111 | [How can you implement multiple inheritance in C#? ](# )|
|112 | [Are private class members inherited to the derived class? ](# )|
|113 | [When and why to use method overloading ](# )|
|114 | [Does C# support multiple-inheritance? ](# )|
|115 | [Where is a protected class-level variable available? ](# )|
|116 | [Are private class-level variables inherited? ](# )|
|117 | [Describe the accessibility modifier “protected internal”. ](# )|
|118 | [Which class is at the top of .NET class hierarchy? ](# )|
|119 | [What does the term immutable mean? ](# )|
|120 | [Can you store multiple data types in System.Array? ](# )|
|121 | [What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? ](# )|
|122 | [How can you sort the elements of the array in descending order? ](# )|
|123 | [What’s the .NET collection class that allows an element to be accessed using a unique key? ](# )|
|124 | [What class is underneath the Sorted List class? ](# )|
|125 | [Will the finally block get executed if an exception has not occurred? ](# )|
|126 | [What’s the C# syntax to catch any possible exception? ](# )|
|127 | [Can multiple catch blocks be executed for a single try statement? ](# )|
|128 | [Explain the three services model commonly know as a three-tier application? ](# )|
|129 | [What is the syntax to inherit from a class in C#? ](# )|
|130 | [Can you prevent your class from being inherited by another class? ](# )|
|131 | [Can you allow a class to be inherited, but prevent the method from being over-ridden? ](# )|
|132 | [When do you absolutely have to declare a class as abstract? ](# )|
|133 | [Why can’t you specify the accessibility modifier for methods inside the interface? ](# )|
|134 | [Can you inherit multiple interfaces? ](# )|
|135 | [ What happens if you inherit multiple interfaces and they have conflicting method names? ](# )|
|136 | [What’s the implicit name of the parameter that gets passed into the set method/property of a class? ](# )|
|137 | [Can you declare an override method to be static if the original method is not static? ](# )|
|138 | [What are the different ways a method can be overloaded? ](# )|
|139 | [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? ](# )|
|140 | [ What’s the implicit name of the parameter that gets passed into the class’ set method? ](# )|
|141 | [How do you inherit from a class in C#? ](# )|
|142 | [Does C# support multiple inheritance? ](# )|
|143 | [ When you inherit a protected class-level variable, who is it available to? ](# )|
|144 | [ Are private class-level variables inherited? ](# )|
|145 | [ Describe the accessibility modifier protected internal.? ](# )|
|146 | [C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write? ](# )|
|147 | [What’s the top .NET class that everything is derived from? ](# )|
|148 | [What does the keyword virtual mean in the method definition? ](# )|
|149 | [Can you declare the override method static while the original method is non-static? ](# )|
|150 | [Can you override private virtual methods? ](# )|
|151 | [When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)? ](# )|
|152 | [Why can’t you specify the accessibility modifier for methods inside the interface? ](# )|
|153 | [And if they have conflicting method names? ](# )|
|154 | [If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor? ](# )|
|155 | [Is it namespace class or class namespace? ](# )|
|156 | [What is the difference between ToString() and Convert.ToString()? ](# )|
|157 | [What is the Difference between int.Parse() and Convert.ToInt32()? ](# )|
|158 | [What is checked block and unchecked block? ](# )|
|159 | [Write a program to get the range of Byte Datatype? ](# )|
|160 | [What is the difference between typeOf() and sizeOf()? ](# )|
|161 | [What is widening and Narrowing? ](# )|
|162 | [How to view an Assembly? ](# )|
|163 | [How to implement Reflection in .Net? ](# )|
|164 | [What are MultiLingual Applications? ](# )|
|165 | [What is the difference between = and == ](# )|
|166 | [What is the use of Codesnippets? ](# )|
|167 | [What is the difference between Array and Collections? ](# )|
|168 | [What is the default Accessmodifier for the members of the class? ](# )|
|169 | [What is the use of constructor? ](# )|
|170 | [When the static constructor will be called? ](# )|
|171 | [ Can we declare Public accessmodifier for static constructor? ](# )|
|172 | [if we declare Main() and static constructor in the same class which one will be called first?](# )|
|173 | [How to Call the Default constructor of one class with the parameterised constructor of same class? ](# )|
|174 | [How to access the constructors of one class to another class? ](# )|
|175 | [Does C#.net Supports Multiple inheritance? ](# )|
|176 | [How to acheive Multiple inheritance in C#.NET? ](# )|
|177 | [what is OverLoading? ](# )|
|178 | [what is Overriding? ](# )|
|179 | [what is use of Properties? ](# )|
|180 | [what is the Difference between Event and Method? ](# )|
|181 | [what are Generics? ](# )|
|182 | [Does generics supports Arthimetic Operators ? ](# )|
|183 | [what is Dynamic Dispatch? ](# )|
|184 | [Which of the following are Build in generic Types? ](# )|
|185 | [In .net for Assemblies we are having StrongName lly in COM Components what is the Strongname? ](# )|
|186 | [Is Versioning applicable to Private assemblies? ](# )|
|187 | [Does .net supports Cross Language Interoparability in CAS? ](# )|
|188 | [What is the importance of “this”keyword? ](# )|
|189 | [C# program to print prime numbers ](# )|
|190 | [C# program to print even numbers ](# )|
|191 | [C# program to print fibonacci series](# )|
|192 | [Palindrome program in C# ](# )|
|193 | [Armstrong Number in C# ](# )|
|194 | [C# Program to reverse number ](# )|
|195 | [C# Program to generate Fibonacci Triangle ](# )|
|196 | [C# Program to Convert Number in Characters ](# )|
|197 | [C# Program to print Number Triangle ](# )|
|198 | [C# Program to swap two numbers without third variable ](# )|
|199 | [Program 2: Using + and - ](# )|
|200 | [Decimal to Binary Conversion Algorithm](# )|
|201 | [C# Program to Convert Number in Characters ](# )|
|202 | [C# program to print multiplication table ](# )|
|203 | [C# program to print alphabets ](# )|
|204 | [Power function in C# ](# )|
|205 | [C# program to count emails by domain ](# )|
|206 | [Reverse characters in a string ](# )|
|207 | [C# program to sort names in ascending and descending order ](# )|
|208 | [C# program to remove duplicates ](# )|
|209 | [Insert space before every upper case letter in a string ](# )|
|210 | [Write a c# program to add two numbers. ](# )|
|211 | [Find smallest and largest number in an integer array ](# )|
|212 | [C# Program to compute factorial of a number ](# )|
|213 | [How to get the total number of decimal places using c# ](# )|
|214 | [How to remove trailing zeros in a decimal - C# Program? ](# )|
|215 | [Write a c program to print M pattern?] (# )|
|216 | [Write the o/p for the below program? ](# )|
# PROGRAMMING CONCEPT
### What is Computer programming?
Computer Programming is also known as programming or coding. Programming is a process which includes processes such as coding, maintaining, updating, debugging, writing, designing (algorithm), etc.
### How programming work?
Programming contains a set of instructions for the computer to perform different tasks. In fact, those instructions are executable commands, each having a different purpose.
### What is debugging?
Debugging is the process of finding and removing errors in a program. In this process, the program is thoroughly checked for errors. Then errors are pointed out and debugged.
### Name different types errors which can occur during the execution of a program?
There are three types of errors which can occur during the execution of a program.
Syntax Errors
Runtime Errors
Logical errors
### When a syntax error occurs?
A syntax error occurs when the program violates one or more grammatical rules of the programming language. These errors are detected at compile time, i.e., when the translator (compiler or interpreter) attempts to translate the program.
### When a runtime error occurs?
A runtime error occurs when the computer is directed to perform an illegal operation by the program such as dividing a number by zero. Runtime errors are the only errors which are displayed immediately during the execution of a program. When these errors occur, the computer stops the execution of the programming and can display a diagnostic message that will help in locating the error.
### When a logical error occurs?
The logical error happens when a program implements a wrong logic. The translator (compiler or interpreter) does not report any error message for a logical error. These errors are the most difficult to locate.
### What is flowchart?
The flowchart is a pictorial representation of a program which helps in understanding the flow of control and data in the algorithm.
### Question: What is an algorithm?
An algorithm is a finite set of steps which, if followed, accomplish a particular task. An algorithm must be clear, finite and effective.
### Question: What do you understand by the term 'Maintain and update the Program'?
Program maintenance is an ongoing process of upgrading the program to accommodate new hardware or software requirements and introducing minor or great improvements. Essentially, it is the expansion, updating and improvement of a program after its installation.
### Question: What are variables?
Variables are named memory locations (memory cells) which are used to store program’s input and its computational results during program execution. As the name suggests, the value of a variable may change during the program execution.
### Question: What are reserved words?
Reserved words or keywords are the words, which have predefined meanings. They have predefined uses and cannot be used or redefined for any other purpose in a programming language.
Examples
IF
ELSE
THEN
### Question: What are Loop?
The loop is a structure which can repeat a set of statements up to a fixed number of times or until a certain criterion is satisfied.
Name different types of loops
Different types of loops are
FOR…NEXT Loop
WHILE…WEND Loop
Nested Loop
### Question: What is the use of FOR…NEXT Loop?
When it is known in advance how many times the loop must be repeated the FOR…NEXT Loop is the most effective option. FOR…NEXT Loop is used to repeat a set of statements to a specific number of times.
### Question: What is the use of WHILE…WEND Loop?
The While loop keeps repeating an action until an associated condition becomes false. This is useful where the programmer does not know in advance how many times the loop will be executed.
### Question: What is the use of Nested Loop?
Loop within a loop is called nested loop.
details%3Fid%3Din.togetu
### Question: What is Documentation?
Documentation is a detailed description of a program’s algorithm, design, coding method, testing, and proper usage. Documentation is valuable for the users who rely upon the program on a day-to-day basis, and for the programmer who may be called on to modify or update it.
### Question: What is the working of a compiler?
A compiler is a unique program that can process statements which are written in a particular programming language and can turn them into machine language or 'code'. This is the working of a complier.
### Question: What do we call the binary form of a target language?
The binary form of a target language is also called 'Binary Code'.
### Question: What are constants?
A constant is a quantity whose value cannot be changed. Unlike a variable, the value stored in a constant can’t be modified during program execution.
Name two types of constants.
Two types of constants are mentioned below:
Numeric Constants
String Constants
### Question: Define Numeric constants.
Numeric constants consist of integers, single precision, or double-precision numbers. Integer constants represent values that are counted and do not have a fractional part, e.g., +56, -678
### Question: Define String constants.
A string constant is a sequence of alphanumeric characters enclosed in double quotation marks. The maximum length of a string constant is 255 characters. For example, 'New York'
### Question: Define Operators.
Operators are symbols which are used to perform certain operations on a data. These include arithmetic, relational, logical, and assignment operators.
### Question: What is an Array?
An array is a collection of contiguous memory locations which can store data of the same type.
### Question: What is subroutine?
A subroutine is a self-contained set of statements that can be used from anywhere in a program. The subroutine performs its specific task and then returns control to the program that calls the subroutine.
### Question: What is the purpose of arithmetic operators?
Arithmetic operators are used to perform arithmetic operations on values (numbers).
### Question: What is the purpose of relational operators?
Relational operators are used to compare two values. These operators always evaluate to true or false. They always produce a non-zero value (in most case 1).
### Question: Define Low-level programming language.
In computer programming, the programming language which provides no generalization from the computer’s 'instruction set architecture' is called a low-level programming language. It usually directs to machine code or assembly language.
### Question: Define High-Level programming language.
In computer programming, the programming language which provides high generalization from the computer’s 'instruction set architecture' is called a high-level programming language. To make the development of a program easier as compared to a low-level programming language, it may use the natural language elements.
### Question: What is Machine code?
Machine code is a language, which can be processed directly by a microprocessor without any need of the previous transformation. Programmers never write programs directly in machine code.
Write a code in 32-bit x86 machine code to calculate the nth Fibonacci number.
8B542408 83FA0077 06B80000 0000C383FA027706 B8010000 00C353BB 01000000B9010000 008D0419 83FA0376 078BD98BC84AEBF1 5BC3
### Question: List some programming languages.
Some programming languages are listed below:
A+
A++
ACC
ALF
APL
BASIC
COBOL
### Question: What is reliability?
It is the proper working of software during a specific period of time. If a program doesn’t work properly during required period then it’s not reliable.
### Question: What is modeling language?
An artificial language that can be used to express information or knowledge or systems in an arrangement which is defined by a reliable number of rules. These rules are also used for interpretation of the meaning of components in the structure.
### Question: Name some modeling languages.
Names of some modeling languages are listed below:
Business Process Modeling Notation
EXPRESS
Extended Enterprise Modeling Language
Flowchart
Fundamental Modeling Concepts
Jackson Structured Programming
Unified Modeling Language
Alloy (specification language
Systems Modeling Language
### Question: What is software testing?
Software testing a process in which software is tested under certain conditions to test the quality of a program. Testing a program is also required to check whether the software provides a good user experience or not.
Tell a few reasons of software testing.
A few reasons for software testing are mentioned below:
Proper working
Satisfying quality
Fulfills the requirements of the user
Can be implemented with the identical
### Question: What is Beta version?
The beta version of software is that version which is not ready for release and can be changed after the feedback from the users. Beta version comes after alpha version.
### Question: What is the working of logical operators?
Logical operators let us combine simple conditions to construct more complex ones (By conditions, we mean an expression evaluating to true or false).
### Question: What is the purpose of assignment operator?
The assignment operator is used to store a value, string or a computational result in a variable.
### Question: What is analyzing a program?
The process in which program is decomposed into sub-problems. Rather on concentrating the bigger problem as a whole, we try to solve each sub-problem separately. This leads to a simple solution. This technique is also known as top-down design.
### Question: What is the working on an algorithm?
Every algorithm performs at least following three steps:
Get data
Perform computation
Display results
### Question: How is the division by zero defined?
Division by zero is undefined.
### Question: What is the meaning of implementation of a program?
Once the program has been tested thoroughly, it must be installed or put into operation at the site where it will be used. This is known as an implementation of the program.
### Question: What are numeric variables?
The variables which can store numeric values are called number variables. Numeric values include both floating point numbers and whole numbers.
### Question: What are string variables?
A string can be defined as a sequence of characters enclosed in double quotations. A string variable can, therefore, store a sequence of characters. The nature of character string is entirely different from the nature of numeric values.
### Question: What are commands?
Commands are executable instructions which are operated in the direct mode. They do not require a preceding line number
### Question: What are statements?
Statements are written as a program, and each statement is preceded by a line number
### Question: What is the execution of a program?
Execution of the program refers to carrying out the instruction of the program. The program must be loaded into memory (RAM) before execution.
### Question: Define variable and constant.
A variable can be defined as a meaningful name that is given to a data storage location in the computer memory that contains a value. Every variable associated with a data type determines what type of value can be stored in the variable, for example an integer, such as 100, a decimal, such as 30.05, or a character, such as 'A'.
You can declare variables by using the following syntax:
;
A constant is similar to a variable except that the value, which you assign to a constant, cannot be changed, as in case of a variable.
Constants must be initialized at the same time they are declared. You can declare constants by using the following syntax:
const int interestRate = 10;
### Question: What is a data type? How many types of data types are there in .NET ?
A data type is a data storage format that can contain a specific type or range of values. Whenever you declare variables, each variable
must be assigned a specific data type. Some common data types include integers, floating point, characters, and strings. The following
are the two types of data types available in .NET:
Value type - Refers to the data type that contains the data. In other words, the exact value or the data is directly stored in this data type. It means that when you assign a value type variable to another variable, then it copies the value rather than copying the reference of that variable. When you create a value type variable, a single space in memory is allocated to store the value (stack memory). Primitive data types, such as int, float, and char are examples of value type variables.
Reference type - Refers to a data type that can access data by reference. Reference is a value or an address that accesses a particular data by address, which is stored elsewhere in memory (heap memory). You can say that reference is the physical address of data, where the data is stored in memory or in the storage device. Some built-in reference types variables in .Net are string, array, and object.
### Question: Mention the two major categories that distinctly classify the variables of C# programs.
Variables that are defined in a C# program belong to two major categories: value type and reference type. The variables that are based on value type contain a value that is either allocated on a stack or allocated in-line in a structure. The variables that are based on reference types store the memory address of a variable, which in turn stores the value and are allocated on the heap. The variables that are based on value types have their own copy of data and therefore operations done on one variable do not affect other variables. The reference-type variables reflect the changes made in the referring variables.
Predict the output of the following code segment:
int x = 42;
int y = 12;
int w;
object o;
o = x;
w = y * (int)o;
Console.WriteLine(w);
/* The output of the code is 504. */
### Question: Which statement is used to replace multiple if-else statements in code.
In Visual Basic, the Select-Case statement is used to replace multiple If - Else statements and in C#, the switch-case statement is used to replace multiple if-else statements.
### Question: What is the syntax to declare a namespace in .NET?
In .NET, the namespace keyword is used to declare a namespace in the code.
The syntax for declaring a namespace in C# is:
namespace UserNameSpace;
The syntax for declaring a namespace in VB is:
Namespace UserNameSpace
### Question: Differentiate between the while and for loop in C#.
The while and for loops are used to execute those units of code that need to be repeatedly executed, unless the result of the specified condition evaluates to false. The only difference between the two is in their syntax. The for loop is distinguished by setting an explicit loop variable.
### Question: What is an identifier?
Identifiers are northing but names given to various entities uniquely identified in a program. The name of identifiers must differ in spelling or casing. For example, MyProg and myProg are two different identifiers. Programming languages, such as C# and Visual Basic, strictly restrict the programmers from using any keyword as identifiers. Programmers cannot develop a class whose name is public, because, public is a keyword used to specify the accessibility of data in programs.
### Question: What does a break statement do in the switch statement?
The switch statement is a selection control statement that is used to handle multiple choices and transfer control to the case statements within its body. The following code snippet shows an example of the use of the switch statement in C#:
switch(choice)
{
case 1:
console.WriteLine(First);
break;
case 2:
console.WriteLine(Second);
break;
default:
console.WriteLine(Wrong choice);
break;
}
In switch statements, the break statement is used at the end of a case statement. The break statement is mandatory in C# and it avoids the fall through of one case statement to another.
### Question: Explain keywords with example.
Keywords are those words that are reserved to be used for a specific task. These words cannot be used as identifiers. You cannot use a keyword to define the name of a variable or method. Keywords are used in programs to use the features of object-oriented programming.
For example, the abstract keyword is used to implement abstraction and the inherits keyword is used to implement inheritance by deriving subclasses in C# and Visual Basic, respectively.
The new keyword is universally used in C# and Visual Basic to implement encapsulation by creating objects.
### Question: Briefly explain the characteristics of value-type variables that are supported in the C# programming language.
The variables that are based on value types directly contain values. The characteristics of value-type variables that are supported in C# programming language are as follows:
1.All value-type variables derive implicitly from the System.ValueTypeclass
2.You cannot derive any new type from a value type
3.Value types have an implicit default constructor that initializes the default value of that type
4.The value type consists of two main categories:
i.Structs - Summarizes small groups of related variables.
ii.Enumerations - Consists of a set of named constants.
Give the syntax of using the while loop in a C# program.
The syntax of using the while loop in C# is:
int i = 0;
while(i < 5) //condition
{
Console.WriteLine({ 0 }, i); //statements
i++;
}
o/p: 0 1 2 3 4
### Question: What is a parameter? Explain the new types of parameters introduced in C# 4.0.
A parameter is a special kind of variable, which is used in a function to provide a piece of information or input to a caller function. These inputs are called arguments. In C#, the different types of parameters are as follows:
1.Value type - Refers that you do not need to provide any keyword with a parameter.
2.Reference type - Refers that you need to mention the ref keyword with a parameter.
3.Output type - Refers that you need to mention the out keyword with a parameter.
4.Optional parameter - Refers to the new parameter introduced in C# 4.0. It allows you to neglect the parameters that have some
predefined default values. The example of optional parameter is as follows:
- public int Sum(int a, int b, int c = 0, int d = 0); /* c and d is optional */
- Sum(10, 20); //10 + 20 + 0 + 0
- Sum(10, 20, 30); //10 + 20 + 30 + 0
- Sum(10, 20, 30, 40); //10 + 20 + 30 + 40
5. Named parameter - Refers to the new parameter introduced in C# 4.0. Now you can provide arguments by name rather than position.
The example of the named parameter is as follows: - public void CreateAccount(string name, string address = unknown, int age = 0);
- CreateAccount(KANSIRIS, age: 30);
- CreateAccount(address: India, name: KANSIRIS);
### Question: Briefly explain the characteristics of reference-type variables that are supported in the C# programming language.
The variables that are based on reference types store references to the actual data. The keywords that are used to declare reference types are:
1.Class - Refers to the primary building block for the programs, which is used to encapsulate variables and methods into a single unit.
2.Interface - Contains only the signatures of methods, properties, events, or indexers.
3.Delegate - Refers to a reference type that is used to encapsulate a named or anonymous method.
### Question: What are the different types of literals?
A literal is a textual representation of a particular value of a type.
The different types of literals in Visual Basic are:
1.Boolean Literals - Refers to the True and False literals that map to the true and false state, respectively.
2.Integer Literals - Refers to literals that can be decimal (base 10), hexadecimal (base 16), or octal (base 8).
3.Floating-Point Literals - Refers to an integer literal followed by an optional decimal point By default, a floating-point literal is
of type Double.
4.String Literals - Refers to a sequence of zero or more Unicode characters beginning and ending with an ASCII double-quote character.
5.Character Literals - Represents a single Unicode character of the Char type.
6.Date Literals - Represents time expressed as a value of the Date type.
7.Nothing - Refers to a literal that does not have a type and is convertible to all types in the type system.
The different types of literals in C# are:
1.Boolean literals - Refers to the True and False literals that map to the true and false states, respectively.
2.Integer literals - Refers to literals that are used to write values of types int, uint, long, and ulong.
3.Real literals - Refers to literals that are used to write values of types float, double, and decimal.
4.Character literals - Represents a single character that usually consists of a character in quotes, such as 'a'.
5.String literals - Refers to string literals, which can be of two types in C#:
i. A regular string literal consists of zero or more characters enclosed in double quotes, such as hello.
ii. A verbatim string literal consists of the @ character followed by a double-quote character, such as @hello.
6.The Null literal - Represents the null-type.
### Question: What is the main difference between sub-procedure and function?
The sub-procedure is a block of multiple visual basic statements within Sub and End Sub statements. It is used to perform certain tasks, such as changing properties of objects, receiving or processing data, and displaying an output. You can define a sub-procedure anywhere in a program, such as in modules, structures, and classes.
We can also provide arguments in a sub-procedure; however, it does not return a new value.The function is also a set of statements within the Function and End Function statements.It is similar to sub - procedure and performs the same task.The main difference between a function and a sub - procedure is that sub - procedures do not return a value while functions do.
Determine the output of the code snippet.
int a = 29;
a--;
a -= ++a;
Console.WriteLine(The value of a is: { 0}, a);
o/p: -1
### Question: Differentiate between Boxing and Unboxing.
When a value type is converted to an object type, the process is known as boxing; whereas, when an object type is converted to a value type, the process is known as unboxing.
Boxing and unboxing enable value types to be treated as objects. Boxing a value type packages it inside an instance of the Object reference type. This allows the value type to be stored on the garbage collected heap. Unboxing extracts the value type from the object. In this example, the integer variable iis boxed and assigned to object obj.
Boxing Example:
public void function1()
{int i =111; object o = i;//implicit unboxing
console.writeline(o); }
Unboxing Example:
public void function1()
{object o =111;
int i = (int)o;//explicit unboxing
console.writeline(i); }
# CSharp (C#)
### Question: What is C#?
C# is the best language for writing Microsoft .NET applications. C# provides the rapid application development found in Visual Basic with the power of C++. Its syntax is similar to C++ syntax and meets 100% of the requirements of OOPs like the following:
• Abstraction
• Encapsulation
• Polymorphism
• Inheritance
### Question: What is an Object?
According to MSDN, "a class or struct definition is like a blueprint that specifies what the type can do. An object is basically a block of memory that has been allocated and configured according to the blueprint. A program may create many objects of the same class. Objects are also called instances, and they can be stored in either a named variable or in an array or collection. Client code is the code that uses these variables to call the methods and access the public properties of the object. In an object-oriented language such as C#, a typical program consists of multiple objects interacting dynamically".
### Question: What is the difference between a struct and a class in C#?
Class and Struct both are the user defined data type but have some major difference:
Struct
• The struct is value type in C# and it inherits from System.Value Type.
• Struct is usually used for smaller amounts of data.
• Struct can’t be inherited to other type.
• A structure can't be abstract.
• No need to create object by new keyword.
• Do not have permission to create any default constructor.
Class
• The class is reference type in C# and it inherits from the System.Object Type.
• Classes are usually used for large amounts of data.
• Classes can be inherited to other class.
• A class can be abstract type.
• We can’t use an object of a class with using new keyword.
• We can create a default constructor.
### Question: What is the difference between Interface and Abstract Class?
### What is an Abstract Class?
An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.
### What is an Interface?
An interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition. In the following example, class ImplementationClass must implement a method named SampleMethod that has no parameters and returns void.
An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn't support multiple inheritance, interfaces are used to implement multiple inheritance.
When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
interface ISampleInterface
{ void SampleMethod(); }
class ImplementationClass : ISampleInterface
{ // Explicit interface member implementation:
void ISampleInterface.SampleMethod()
{ // Method implementation.
}
static void Main()
{ // Declare an interface instance.
ISampleInterface obj = new ImplementationClass();
// Call the member.
obj.SampleMethod();
} }
Feature
Interface
Abstract class
Multiple inheritance
A class may inherit several interfaces.
A class may inherit only one abstract class.
Default implementation
An interface cannot provide any code, just the signature.
An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modifiers
An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public
An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral
Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.
An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity
If various implementations only share method signatures then it is better to use Interfaces.
If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
Speed
Requires more time to find the actual method in the corresponding classes.
Fast
Adding functionality (Versioning)
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants
No fields can be defined in interfaces
An abstract class can have fields and constraints defined
### Question: What is enum in C#?
An enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is used to declare an enumeration. It is a primitive data type, which is user defined.
An enum type can be an integer (float, int, byte, double etc.). But if you used beside int it has to be cast.
An enum is used to create numeric constants in .NET framework. All the members of enum are of enum type. There must be a numeric value for each enum type.
The default underlying type of the enumeration element is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.
enum Dow {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
Some points about enum-
• Enums are enumerated data type in c#.
• Enums are not for end-user, they are meant for developers.
• Enums are strongly typed constant. They are strongly typed, i.e. an enum of one type may not be implicitly assigned to an enum of
another type even though the underlying value of their members is the same.
• Enumerations (enums) make your code much more readable and understandable.
• Enum values are fixed. Enum can be displayed as a string and processed as an integer.
• The default type is int, and the approved types are byte, sbyte, short, ushort, uint, long, and ulong.
• Every enum type automatically derives from System.Enum and thus we can use System.Enum methods on enums.
• Enums are value types and are created on the stack and not on the heap.
### Question: What is the difference between “continue” and “break” statements in C#?
Using break statement, you can 'jump out of a loop' whereas by using continue statement, you can 'jump over one iteration' and then resume your loop execution.
Break Statement Example-
using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace break_example
{
{
Class brk_stmt
{
public static void main(String[] args) {
for (int i = 0; i <= 5; i++) {
if (i == 4) {continue; }
Console.ReadLine(“The number is” + i);
}
}
}
}
Output:
The number is 0;
The number is 1;
The number is 2;
The number is 3;
Continue Statement Example
using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace continue_example
{
Class cntnu_stmt
{
public static void main(String[]
{
for (int i = 0; i <= 5; i++)
{
if (i == 4)
{
continue;
}
Console.ReadLine(“The number is” +i);
}
}
}
}
Output:
The number is 1;
The number is 2;
The number is 3;
The number is 5;
### Question: What is the difference between constant and readonly in c#?
Constants perform the same tasks as read-only variables with some differences. The differences between constants and read-only are
Constants:
1.Constants are dealt with at compile-time.
2.Constants supports value-type variables.
3.Constants should be used when it is very unlikely that the value will ever change.
Read-only:
1.Read-only variables are evaluated at runtime.
2.Read-only variables can hold reference type variables.
3.Read-only variables should be used when run-time calculation is required.
See the example
We have a Test Class in which we have two variables one is readonly and another is constant.
class Test {
readonly int read = 10;const int cons = 10;
public Test() { read = 100; cons = 100; }
public void Check() { Console.WriteLine("Read only : {0}", read);
Console.WriteLine("const : {0}", cons);
}
}
Here I was trying to change the value of both the variables in constructor but when I am trying to change the constant it gives an error to change their value in that block which have to call at run time.
So finally remove that line of code from class and call this Check() function like the following code snippet:
class Program {
static void Main(string[] args) {
Test obj = new Test(); obj.Check(); Console.ReadLine();
}
}
class Test {
readonly int read = 10;
const int cons = 10;
public Test() { read = 100;}
public void Check() {
Console.WriteLine("Read only : {0}", read);
Console.WriteLine("const : {0}", cons);
}
}
Output:
### Question: What is the difference between ref and out keywords?
In C Sharp (C#) we can have three types of parameters in a function. The parameters can be in parameter (which is not returned back to the caller of the function), out parameter and ref parameter. We have lots of differences in both of them.
Both ref and out are treated differently at run time and they are treated the same at compiler
properties are not variables, therefore it cannot be passed as an out or ref parameter
Ref
The parameter or argument must be initialization first before it is passed to ref
A called method is required to assign or initialize a value of a parameter (which is passed to an out)before returning to the calling method
Passing a parameter value by ref is useful when the called method is also needed to modify the pass parameter
A parameter value must be initialized within calling method before its use
When we use ref data can be passed bidirectionally
Out
It is compulsory to initialize a parameter or argument before it is passed to an out
It is not required to assign or initialize the value of a parameter(which is passed by ref ) before returning to the calling method
Declaring a parameter to an out method is when multiple values need to be returned for function or method
It is not compulsory to initialize a parameter value before using it in a calling method
When we use out data is passed only in unidirectional way (from the called method caller )
### Question: Can “this” be used within a static method?
We can't use this in static method because keyword 'this' returns a reference to the current instance of the class containing it.
Static methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class and call with the name of a class not by instance so we can’t use this keyword in the body of static Methods, but in case of Extension Methods we can use it the functions parameters. Let’s have a look on “this” keyword.
The "this" keyword is a special type of reference variable that is implicitly defined within each constructor and non-static method as a first parameter of the type class in which it is defined. For example, consider the following class written in C#.
Let me explain you with a simple practical demonstration.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace this_example
{
class Program
{
public class Demo
{
int age;
string name;
public Demo(int age, string name)
{
age = age;
name = name;
}
public void Show()
{
Console.WriteLine("Your age is :" + age.ToString());
Console.WriteLine("Your name is : " + name);
} }
static void Main(string[] args)
{
int _age;
string _name;
Console.WriteLine("Enter your age : " );
_age=Int32.Parse(Console.ReadLine());
Console.WriteLine("Enter your name : ");
_name=Console.ReadLine();
Demo obj = new Demo(_age, _name);
obj.Show();
Console.ReadLine();
} }}
Output of the above program will be:
See your not getting any value. Because in the program the local data members age, name have precedence over instance members.
Note the program will give a warning not error (Assignment made to some variable; did you mean to assign something else?)
We have to use this keyword to refer to the instance members.
Now I do a slight change in the program using this keyword.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace this_example
{
class Program
{
public class Demo
{
int age;
string name;
public Demo(int age, string name)
{ // Have made change here included this keyword
this.age = age; this.name = name; }
public void Show()
{ Console.WriteLine("Your age is :" + age.ToString());
Console.WriteLine("Your name is : " + name); } }
static void Main(string[] args)
{ int _age; string _name;
Console.WriteLine("Enter your age : " );
_age=Int32.Parse(Console.ReadLine());
Console.WriteLine("Enter your name : ");
_name=Console.ReadLine();
Demo obj = new Demo(_age, _name);
obj.Show();
Console.ReadLine();
} } }
See the output.
I think now this keyword would be clear to you.
The program is not complete implementation of this keyword but it tries to make you explain how it works and when to use.
### Question: Define Property in C# .net?
Properties are members that provide a flexible mechanism to read, write or compute the values of private fields, in other words by the property we can access private fields. In other words we can say that a property is a return type function/method with one parameter or without a parameter. These are always public data members. It uses methods to access and assign values to private fields called accessors.
### Question: Now question is what are accessors?
The get and set portions or blocks of a property are called accessors. These are useful to restrict the accessibility of a property, the set accessor specifies that we can assign a value to a private field in a property and without the set accessor property it is like a read-only field. By the get accessor we can access the value of the private field, in other words it returns a single value. A Get accessor specifies that we can access the value of a field publicly.
We have the three types of properties
• Read/Write.
• ReadOnly.
• WriteOnly
### Question: What is extension method in c# and how to use them?
Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. An extension method is a special kind of static method, but they are called as if they were instance methods on the extended type.
### Question : How to use extension methods?
An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.
Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.
Like: suppose we have a class like below:
public class Class1 {
public string Display() {
return ("I m in Display");}
public string Print() {
return ("I m in Print");}}
Now we need to extend the definition of this class so m going to create a static class to create an extinction method like:
public static class XX {
public static void NewMethod(this Class1 ob) {
Console.WriteLine("Hello I m extended method");}}
Here I just create a method that name is NewMethod with a parameter using this to define which type of data I need to be extend, now
let’s see how to use this function.
Code will look like that:
class Program {
static void Main(string[] args) {
Class1 ob = new Class1(); ob.Display(); ob.Print(); ob.NewMethod(); Console.ReadKey();
}
}
Output will be:
### Question: What is the difference between string and StringBuilder in c#?
StringBuilder and string both use to store string value but both have many differences on the bases of instance creation and also for
performance:
String:
String is an immutable object. Immutable like when we create string object in code so we cannot modify or change that object in any
operations like insert new value, replace or append any value with existing value in string object, when we have to do some operations
to change string simply it will dispose the old value of string object and it will create new instance in memory for hold the new value
in string object like:
class program{static void main(string[] args)
{string val = “hello”;
//create a new string instance instead of changing the old one
val += “am”;
val +=”nithin pandit”;
console.writeline(val);
}
}
Note:
• It’s an immutable object that holds string value.
• Performance wise string is slow because its’ create a new instance to override or change the previous value.
• String belongs to System namespace.
StringBuilder:
System.Text.Stringbuilder is mutable object which also hold the string value, mutable means once we create a System.Text.Stringbuilder
object we can use this object for any operation like insert value in existing string with insert functions also replace or append
without creating new instance of System.Text.Stringbuilder for every time so it’s use the previous object so it’s work fast as compare
than System.String. Let’s have an example to understand System.Text.Stringbuilder like:
class program
{
static void main(string[]args)
{
stringbuilder val =new stringbuilder(“”);
val.append(“hello);
val.append(“am nitin pandit:)”);
console.writeline(val);}}
Note:
• StringBuilder is a mutable object.
• Performance wise StringBuilder is very fast because it will use same instance of StringBuilder object to perform any operation like insert value in existing string.
• StringBuilder belongs to System.Text.Stringbuilder namespace.
String Example
string colors;
colors += "red";
colors += "blue";
colors += "green";
In the above code string color will alter 3 times, each time the code perform a string operation (+=). That mean 3 new string created in the memory. When you perform repeated operation to a string, the overhead associated with creating a new String object can be costly.
StringBuilder Example
StringBuilder sb = new StringBuilder("");
sb.Append("red");
sb.Append("blue");
sb.Append("green ");
string colors = sb.ToString();
In the above code the StringBuilder object will alter 3 times, each time the code attempt a StringBuilder operation without creating a new object. That means, using the StringBuilder class can boost performance when concatenating many strings together in a loop.
### Question: What are delegates in C# and uses of delegates?
A delegate object encapsulates a reference to a method.
C# delegates are same as pointers to functions, in C or C++. A delegate Object is a reference type variable that use to holds the
reference to a method. The reference can be changed at runtime which is hold by an object of delegate, a delegate object can hold many
functions reference which is also known as Invocation List that refers functions in a sequence FIFO, we can new functions ref in this
list at run time by += operator and can remove by -= operator.
Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the
System.Delegate class.
Let’s see how to use Delegate with Example:
### Question : What is sealed class in c#?
Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as a sealed class, the class cannot be inherited.
In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET the Not Inheritable keyword serves the purpose of sealed. If a class is derived from a sealed class then the compiler throws an error.
If you have ever noticed, structs are sealed. You cannot derive a class from a struct.
The following class definition defines a sealed class in C#:
// Sealed class
sealed class SealedClass
{ }
### Question : What are partial classes?
A partial class is only use to splits the definition of a class in two or more classes in a same source code file or more than one source files. You can create a class definition in multiple files but it will be compiled as one class at run time and also when you’ll create an instance of this class so you can access all the methods from all source file with a same object.
Partial Classes can be create in the same namespace it’s doesn’t allowed to create a partial class in different namespace. So use “partial” keyword with the entire class name which you want to bind together with the same name of class in same namespace, let’s have an example:
### Question : What is IEnumerable<> in c#?
IEnumerable is the parent interface for all non-generic collections in System.Collections namespace like ArrayList, HastTable etc. that can be enumerated. For the generic version of this interface as IEnumerable which a parent interface of all generic collections class in System.Collections.Generic namespace like List<> and more.
In System.Collections.Generic.IEnumerable have only a single method which is GetEnumerator() that returns an IEnumerator. IEnumerator provides the power to iterate through the collection by exposing a Current property and Move Next and Reset methods, if we doesn’t have this interface as a parent so we can’t use iteration by foreach loop or can’t use that class object in our LINQ query.
### Question : What is difference between late binding and early binding in c#?
Early Binding and Late Binding concepts belongs to polymorphism so let’s see first about polymorphism:
Polymorphism is an ability to take more than one form of a function means with a same name we can write multiple functions code in a same class or any derived class.
Polymorphism we have 2 different types to achieve that:
• Compile Time also known as Early Binding or Overloading.
• Run Time also known as Late Binding or Overriding.
Compile Time Polymorphism or Early Binding: In Compile time polymorphism or Early Binding we will use multiple methods with same name but different type of parameter or may be the number or parameter because of this we can perform different-different tasks with same method name in the same class which is also known as Method overloading.
See how we can do that by the following example:
RunTime Polymorphism or Late Binding: Runtime polymorphism also known as late binding, in Run Time polymorphism or Late Binding we can do use same method names with same signatures means same type or same number of parameters but not in same class because compiler doesn’t allowed that at compile time so we can use in derived class that bind at run time when a child class or derived class object will instantiated that’s way we says that Late Binding.
For that we have to create my parent class functions as partial and in driver or child class as override functions with override keyword.
Like as following example:
### Question : What are the differences between IEnumerable and IQueryable?
Before the differences learn what is IEnumerable and IQueryable.
IEnumerable:
Is the parent interface for all non-generic collections in System.Collections namespace like ArrayList, HastTable etc. that can be enumerated. For the generic version of this interface as IEnumerable which a parent interface of all generic collections class in
System.Collections.Generic namespace like List< > and more.
IQueryable:
As per MSDN IQueryable interface is intended for implementation by query providers. It is only supposed to be implemented by providers that also implement IQueryable. If the provider does not also implement IQueryable, the standard query operators cannot be used on the provider's data source.
The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed. The definition of "executing an expression tree" is specific to a query provider. For example, it may involve translating the expression tree to an appropriate query language for the underlying data source. Queries that do not return enumerable results are executed when the Execute method is called.
Ienumerable
iqueryable
ienumerable belongs to system.collection namespace
inquerable belongs to system.linq.namespace
ienumerable is the best way to write query on collections data type like list,array etc
iqueryable is the best way to write query data like remote database,service collections
ienumerable is the return type for linq to object and linq to xml queries
iqueryable is the return type of linq to sql queries
ienumerable doesnt support lazy loading so it's not a recommended approach for paging kind of scenarios
iquerable support lazy loading so we can also use in paging kind of scenarios
extension methods are supports by ienumerable takes funtional objects for linq querys
iqueryable implements ienumerable so indirectly its also supports extensions methods
### Question : What happens if the inherited interfaces have conflicting method names?
If we implement multiple interface in the same class with conflict method name so we don’t need to define all or in other words we can say if we have conflict methods in same class so we can’t implement their body independently in the same class coz of same name and same signature so we have to use interface name before method name to remove this method confiscation let’s see an
example:
interface testInterface1 {
void Show(); }
interface testInterface2 {
void Show(); }
class Abc: testInterface1,
testInterface2 {
void testInterface1.Show() {
Console.WriteLine("For testInterface1 !!"); }
void testInterface2.Show() {
Console.WriteLine("For testInterface2 !!"); }}
Now see how to use those in a class:
class Program {
static void Main(string[] args) {
testInterface1 obj1 = new Abc();
testInterface1 obj2 = new Abc();
obj1.Show();
obj2.Show();
Console.ReadLine(); } }
### Question : What are the Arrays in C#.Net?
Arrays are powerful data structures for solving many programming problems. You saw during the creation of variables of many types that they have one thing in common; they hold information about a single item, for instance an integer, float and string type and so on. So what is the solution if you need to manipulate sets of items? One solution would be to create a variable for each item in the set but again this leads to a different problem. How many variables do you need?
So in this situation Arrays provide mechanisms that solves problem posed by these questions. An array is a collection of related items, either value or reference type. In C# arrays are immutable such that the number of dimensions and size of the array are fixed.
Arrays Overview-
An array contains zero or more items called elements. An array is an unordered sequence of elements. All the elements in an array are of the same type (unlike fields in a class that can be of different types). The elements of an array accessed using an integer index that always starts from zero. C# supports single-dimensional (vectors), multidimensional and jagged arrays.
Elements are identified by indexes relative to the beginning of the arrays. Indexes are also commonly called indices or subscripts and are placed inside the indexing operator ([]). Access to array elements is by their index value that ranges from 0 to (length-1).
Array Properties
• The length cannot be changed once created.
• Elements are initialized to default values.
• Arrays are reference types and are instances of System.Array.
• Their number of dimensions or ranks can be determined by the Rank property.
• An array length can be determined by the GetLength() method or Length property.
### Question : What is the Constructor Chaining in C#?
Constructor Chaining is a way to connect two or more classes in a relationship as Inheritance, in Constructor Chaining every child class constructor is mapped to parent class Constructor implicitly by base keyword so when you create an instance of child class to it’ll call parent’s class Constructor without it inheritance is not possible.
### Question : What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
Clone - Method creates a shallow copy of an array. A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to.
CopyTo - The Copy static method of the Array class copies a section of an array to another array. The CopyTo method copies all the elements of an array to another one-dimension array. The code listed in Listing 9 copies contents of an integer array to an array of object types.
### Question : Can Multiple Catch Blocks executed in c#?
We can use multiple Catches block with every try but when any Exceptions is throw by debugger so every catches match this exception type with their signature and catch the exception by any single catch block so that means we can use multiple catches blocks but only one can executed at once like:
using System;
class MyClient {
public static void Main() {
int x = 0;
int div = 0;
try {div = 100 / x;
Console.WriteLine("Not executed line");
} catch (DivideByZeroException de) {
Console.WriteLine("DivideByZeroException");
} catch (Exception ee) {
Console.WriteLine("Exception");
} finally {
Console.WriteLine("Finally Block"); }
Console.WriteLine("Result is {0}", div); } }
### Question : Difference between Throw Exception and Throw Clause.
The basic difference is that the Throw exception overwrites the stack trace and this makes it hard to find the original code line number that has thrown the exception.
Throw basically retains the stack information and adds to the stack information in the exception that it is thrown.
Let us see what it means rather speaking so many words to better understand the differences. I am using a console application to easily test and see how the usage of the two differs in their functionality.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestingThrowExceptions {
class Program {
public void ExceptionMethod() {
throw new Exception("Original Exception occurred in ExceptionMethod");
}
static void Main(string[] args) {
Program p = new Program();
try {p.ExceptionMethod(); }
catch (Exception ex) {
throw ex;
}
}
}
}
Now run the code by pressing the F5 key of the keyboard and see what happens. It returns an exception
### Question : What is Indexer in C# .Net?
Indexer allows classes to be used in more intuitive manner. C# introduces a new concept known as Indexers which are used for treating an object as an array. The indexers are usually known as smart arrays in C#. They are not essential part of object-oriented programming.
An indexer, also called an indexed property, is a class property that allows you to access a member variable of a class using the features of 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.
Creating an Indexer:
< modifier >
this[argument list] {
get {// your get block code}
set {// your set block code}}
In the above code:
- can be private, public, protected or internal.
- can be any valid C# types.
### Question : What is multicast delegate in c#?
A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called.
Delegate can invoke only one method reference has been encapsulated into the delegate.it is possible for certain delegate to hold and invoke multiple methods such delegate called multicast delegates.multicast delegates also know as combinable delegates, must satisfy the following conditions:
• The return type of the delegate must be void. None of the parameters of the delegate type can be delegate type can be declared as output parameters using out keywords.
• Multicast delegate instance that created by combining two delegates, the invocation list is formed by concatenating the invocation list of two operand of the addition operation. Delegates are invoked in the order they are added.
Implement Multicast Delegates Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
delegate void MDelegate();
class DM {
static public void Display() {
Console.WriteLine("Meerut") }
static public void print() {
Console.WriteLine("Roorkee"); } }
class MTest {
public static void Main() {
MDelegate m1 = new MDelegate(DM.Display);
MDelegate m2 = new MDelegate(DM.print);
MDelegate m3 = m1 + m2;
MDelegate m4 = m2 + m1;
MDelegate m5 = m3 - m2;
m3(); m4(); m5();
}
}
### Question : Difference between Equality Operator (==) and Equals() Method in C#.
Both the == Operator and the 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.
In this example we assigned a string variable to another variable. A string is a reference type and in the following example, a string variable is assigned to another string variable so they are referring to the same identity in the heap and both have the same content so you get True output for both the == Operator and the Equals() method.
using System;
namespace ComparisionExample {
class Program {
static void Main(string[] args) {
string name = "Kansiris";
string myName = name;
Console.WriteLine("== operator result is {0}", name == myName);
Console.WriteLine("Equals method result is {0}", name.Equals(myName));
Console.ReadKey();
}
}
}
### Question : Difference between “is” and “as” operator in C#.
"is" operator-
In the C# language, we use the "is" operator to check the object type. If the two objects are of the same type, it returns true and false if not.
Let's understand the preceding from a small program. We defined the following two classes:
class Speaker {
public string Name { get; set; } }
class Author {
public string Name { get; set; } }
Now, let's try to check the preceding types as:
• var speaker = new Speaker { Name="Gaurav Kumar Arora"};
• We declared an object of Speaker as in the following:
• var isTrue = speaker is Speaker;
• In the preceding, we are just checking the matching type. Yes, our speaker is an object of Speaker type.
• Console.WriteLine("speaker is of Speaker type:{0}", isTrue);
So, the results as true.
But, here we get false:
• var author = new Author { Name = "Gaurav Kumar Arora" };
• var isTrue = speaker is Author;
• Console.WriteLine("speaker is of Author type:{0}", isTrue);
Because our speaker is not an object of Author type.
"as" operator-
The "as" operator behaves similar to the "is" operator. The only difference is it returns the object if both are compatible to that
type else it returns null.
Let's understand the preceding with a small snippet as in the following:
public static string GetAuthorName(dynamic obj)
{ Author authorObj = obj as Author;
return (authorObj != null) ? authorObj.Name : string.Empty; }
We have a method that accepts dynamic objects and returns the object name property if the object is of the Author type.
Here, we declared two objects:
var speaker = new Speaker { Name="Gaurav Kumar Arora"};
var author = new Author { Name = "Gaurav Kumar Arora" };
The following returns the "Name" property:
var authorName = GetAuthorName(author);
Console.WriteLine("Author name is:{0}", authorName);
It returns an empty string:
authorName = GetAuthorName(speaker);
Console.WriteLine("Author name is:{0}", authorName);
### Question : How to use Nullable<> Types in .Net?
A nullable Type is a data type is that contain the defined data type or the value of null. You should note here that here variable datatype has been given and then only it can be used.
This nullable type concept is not compatible with "var".
I will explain this with syntax in next section.
Declaration:
Any DataType can be declared nullable type with the help of operator "?".
Example of the syntax is as Follows:
int? i = null;
As discussed in previous section "var" is not compatible with this Nullable Type. So we will have Compile Time error if we are
declaring something like:
var? i = null;
Though following syntax is completely fine:
var i = 4;
### Question : Different Ways of Method can be overloaded.
Method overloading is a way to achieve compile time Polymorphism where we can use a method with the same name but different signature, Method overloading is done at compile time and we have multiple way to do that but in all way method name should be same.
◦ Number of parameter can be different.
◦ Types of parameter can be different.
◦ Order of parameters can be different.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Hello_Word {
class overloding {
public static void Main() {
Console.WriteLine(volume(10));
Console.WriteLine(volume(2.5F, 8));
Console.WriteLine(volume(100L, 75, 15));
Console.ReadLine();
}
static int volume(int x) { return (x * x * x); }
static double volume(float r, int h) { return (3.14 * r * r * h); }
static long volume(long l, int b, int h) { return (l * b * h);
}
}
}
Note:
If we have a method that have two parameter object type and have a same name method with two integer parameter so when we call that method with int value so it’ll call that method have integer parameter instead of object type parameters method.
### Question : What is an Object Pool in .Net?
Object Pooling is something that tries to keep a pool of objects in memory to be re-used later and hence it will reduce the load of object creation to a great extent. This article will try to explain this in detail. The example is for an Employee object, but you can make it general by using Object base class.
What does it mean?
Object Pool is nothing but a container of objects that are ready for use. Whenever there is a request for a new object, the pool manager will take the request and it will be served by allocating an object from the pool.
How it works?
We are going to use Factory pattern for this purpose. We will have a factory method, which will take care about the creation of objects. Whenever there is a request for a new object, the factory method will look into the object pool (we use Queue object). If there is any object available within the allowed limit, it will return the object (value object), otherwise a new object will be created and give you back.
### Question : What are generics in c#.net?
Generics allow you to delay the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.
You write the specifications for the class or the method, with substitute parameters for data types. When the compiler encounters a constructor for the class or a function call for the method, it generates code to handle the specific data type.
Generic classes and methods combine reusability, type safety and efficiency in a way that their non-generic counterparts cannot.
Generics are most frequently used with collections and the methods that operate on them. Version 2.0 of the .NET Framework class library provides a new namespace,
System.Collections.Generic, which contains several new generic-based collection classes. It is recommended that all applications that target the .NET Framework 2.0 and later use the new generic collection classes instead of the older non-generic counterparts such as ArrayList.
Features of Generics:
Generics is a technique that enriches your programs in the following ways:
• It helps you to maximize code reuse, type safety and performance.
• You can create generic collection classes. The .NET Framework class library contains several new generic collection classes in the
System.Collections.Generic namespace. You may use these generic collection classes instead of the collection classes in the System.Collections namespace.
• You can create your own generic interfaces, classes, methods, events and delegates.
• You may create generic classes constrained to enable access to methods on specific data types.
• You may get information on the types used in a generic data type at run-time using reflection.
### Question : Describe the accessibility modifiers in c#.Net
Access modifiers are keywords used to specify the declared accessibility of a member or a type.
Why to use access modifiers?
Access modifiers are an integral part of object-oriented programming. They support the concept of encapsulation, which promotes the idea of hiding functionality. Access modifiers allow you to define who does or doesn't have access to certain features. In C# there are 5 different types of Access Modifiers:
Modifier
Description
Public
There are no restrictions on accessing public members
Private
Access is limited to within the class definition. This is the default access modifier type if none is formally specified
Protected
Access is limited to within the class definition and any class that inherits from the class
Internal
Access is limited exclusively to classes defined within the current project assembly
Protected internal
Access is limited to current assembly
### Question : What is Virtual Method in C#?
A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as derived the class. It is used when a method's basic functionality is the same but sometimes more functionality is needed in the derived class. A virtual method is created in the base class that can be overridden in the derived class. We create a virtual method in the base class using the virtual keyword and that method is overridden in the derived class using the override keyword.
When a method is declared as a virtual method in a base class then that method can be defined in a base class and it is optional for the derived class to override that method. The overriding method also provides more than one form for a method. Hence it is also an example for polymorphism.
When a method is declared as a virtual method in a base class and that method has the same definition in a derived class then there is no need to override it in the derived class. But when a virtual method has a different definition in the base class and the derived class then there is a need to override it in the derived class.
When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.
Virtual Method:
1. By default, methods are non-virtual. We can't override a non-virtual method.
2. We can't use the virtual modifier with the static, abstract, private or override modifiers.
### Question : What is the Difference between Array and ArrayList in C#.Net?
Array
ArrayList
Array uses the vector array to store the elements
ArrayList uses the linked list to store the elements
Size of the array must be defined until redeem used(vb)
No need to specify the storage size
Array is specific data type storage
ArrayList can be stored everything as object
No need to do the typecasting
Every time type casting has to do
It will not lead to runtime exception
It leads to the runtime error exception
Element cannot be inserted or deleted in between
Elements can be inserted and deleted
There is no build in members to do ascending or descending
Arraylist has many methods to do operation like sort insert, remove, binarysearch, etc
### Question : What you understand by Value types and Reference types in C#.Net?
In C# data types can be of two types: Value Types and Reference Types. Value type variables contain their object (or data) directly. If
we copy one value type variable to another then we are actually making a copy of the object for the second variable. Both of them will
independently operate on their values, Value Type member will locate into Stack and reference member will locate in Heap always.
Let consider each case briefly:
• Pure Value Type: Here I used a structure as a value type. It has an integer member. I created two instances of this structure. Afterwards I assigned second instance to the first one. Then I changed the state of second instance, but it hasn't effect the first one, as whole items are value type and assignments on those types will copy only values not references i.e. in a Value Type assignment, all instances have its own local copy of members.
• Pure Reference Type: I created a class and added a "DataTable" as a Reference Type member for this class. Then I performed the assignments just like below. But the difference is that on changing the state of second instance, the state of first instance will automatically alter. So in a Reference Type assignment both Value and Reference will be assigned i.e. all instances will point to the single object.
• Value Type with Reference Type: This case and the last case to come are more interesting. I used a structure in this particular scenario also. But this time it includes a Reference Type (A Custom Class Object) Member besides a Value Type (An Integer) Member. When you performing the assignments, it seems like a swallow copy, as Value Type member of first instance won't effected, but the Reference Type member will alter according to the second instance. So in this particular scenario, assignment of Reference Type member produced a reference to a single object and assignment of Value Type member produced a local copy of that member.
• Reference Type With Value Type : Contrary to the above case, in this scenario, both Reference & Value Types will be affected. I.e. a Value Type member in a Reference Type will be shared among its instances.
### Question : What is Serialization?
Serialization means saving the state of your object to secondary memory, such as a file. Suppose you have a business layer where you have many classes to perform your business data. Now suppose you want to test whether your business classes give the correct data out without verifying the result from the UI or from a database. Because it will take some time to process.
Here comes Serialization. You will serialize all your necessary business classes and save them into a text or XML file, on your hard disk. So you can easily test your desired result by comparing your serialized saved data with, your desired output data. You can say it is a little bit of autonomic unit testing performed by the developer.
There are three types of serialization:
• Binary serialization (Save your object data into binary format).
• Soap Serialization (Save your object data into binary format; mainly used in network related communication).
• Xml Serialization (Save your object data into an XML file).
### Question : What is the use of using statement in C#?
The .Net Framework provides resource management for managed objects through the garbage collector - You do not have to explicitly allocate and release memory for managed objects. Clean-up operations for any unmanaged resources should perform in the destructor in C#. To allow the programmer to explicitly perform these clean-up activities, objects can provide a Dispose method that can be invoked when the object is no longer needed. The using statement in C# defines a boundary for the object outside of which, the object is automatically destroyed. The using statement is excited when the end of the "using" statement block or the execution exits the "using" statement block indirectly, for example - an exception is thrown. The "using" statement allows you to specify multiple resources in a single statement. The object could also be created outside the "using" statement. The objects specified within the using block must implement the IDisposable interface. The framework invokes the Dispose method of objects specified within the "using" statement when the block is exited.
### Question : What is jagged array in C#.Net?
A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays." A special type of array is introduced in C#. A Jagged Array is an array of an array in which the length of each array index can differ.
Example:
int[][] jagArray = new int[5][];
In the above declaration the rows are fixed in size. But columns are not specified as they can vary.
Declaring and initializing jagged array:
int[][] jaggedArray = new int[5][];
jaggedArray[0] = new int[3];
jaggedArray[1] = new int[5];
jaggedArray[2] = new int[2];
jaggedArray[3] = new int[8];
jaggedArray[4] = new int[10];
jaggedArray[0] = new int[] { 3, 5, 7, };
jaggedArray[1] = new int[] { 1, 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 1, 6 };
jaggedArray[3] = new int[] { 1, 0, 2, 4, 6, 45, 67, 78 };
jaggedArray[4] = new int[] { 1, 0, 2, 4, 6, 34, 54, 67, 87, 78 };
### Question : What is Multithreading with .NET?
The real usage of a thread is not about a single sequential thread, but rather using multiple threads in a single program. Multiple threads running at the same time and performing various tasks is referred as Multithreading. A thread is considered to be a lightweight process because it runs within the context of a program and takes advantage of resources allocated for that program.
A single-threaded process contains only one thread while a multithreaded process contains more than one thread for execution.
System.Threading Namespace:
Like many other features, in .NET, System.Threading is the namespace that provides various types to help in construction of multithreaded applications.
Type
Description
Thread
It represents a thread that executes within the CLR. Using this we can produce additional threads in an application domain
Mutex
It is used for synchronization between application domains
Monitor
It implements synchronization of objects using locks and wait
Smaphore
It allows limiting the number of threads that can access a resource concurrently
Interlock
It provides atomic operations for variables that are shared by multiple threads
Threadpool
It allows you to interact with the CLR maintained thread pool
Thread
This represents the priority levels such as high,low and normal
### Question : Explain Anonymous type in C#?
Anonymous types allow us to create new type without defining them. This is way to defining read only properties into a single object without having to define type explicitly. Here Type is generating by the compiler and it is accessible only for the current block of code. The type of properties is also inferred by the compiler.
We can create anonymous types by using “new” keyword together with the object initializer.
Example:
var anonymousData = new
{ ForeName = "Jignesh",
SurName = "Trivedi" };
Console.WriteLine("First Name : " + anonymousData.ForeName);
Anonymous Types with LINQ Example:
Anonymous types are also used with the "Select" clause of LINQ query expression to return subset of properties.
Example:
If Any object collection having properties called FirstName , LastName, DOB etc. and you want only FirstName and LastName after the Querying the data then.
class MyData {
public string FirstName {get; set;}
public string LastName {get;. set;}
public DateTime DOB {get; set;}
public string MiddleName {get; set; } }
static void Main(string[] args) {
// Create Dummy Data to fill Collection.
List < MyData > data = new List < MyData > ();
data.Add(new MyData {FirstName = "Jignesh", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(1990, 12, 30)});
data.Add(new MyData {FirstName = "Tejas", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(1995, 11, 6) 64});
data.Add(new MyData {FirstName = "Rakesh", LastName = "Trivedi", MiddleName = "G", DOB = new Date Time(1993, 10, 8) });
data.Add(new MyData {FirstName = "Amit", LastName = "Vyas", MiddleName = "P", DOB = newDateTime (1983, 6, 15)});
data.Add(new MyData {FirstName = "Yash", LastName = "Pandiya", MiddleName = "K", DOB = newDateTime(1988, 7, 20)}); }
var anonymousData = from pl in data
select new { pl.FirstName, pl.LastName };
foreach(var m in anonymousData) {
Console.WriteLine("Name : " + m.FirstName + " " + m.LastName); } }
### Question : Explain Hashtable in C#?
A Hashtable is a collection that stores (Keys, Values) pairs. Here, the Keys are used to find the storage location and are immutable and cannot have duplicate entries in the Hashtable. The .Net Framework has provided a Hash Table class that contains all the functionality required to implement a hash table without any additional development. The hash table is a general-purpose dictionary collection. Each item within the collection is a DictionaryEntry object with two properties: a key object and a value object. These are known as Key/Value. When items are added to a hash table, a hashcode is generated automatically. This code is hidden from the developer. All access to the table's values is achieved using the key object for identification.
As the items in the collection are sorted according to the hidden hash code, the items should be considered to be randomly ordered.
The Hashtable Collection: The Base Class libraries offers a Hashtable Class that is defined in the System.Collections namespace, so you don't have to code your own hash tables. It processes each key of the hash that you add every time and then uses the hash code to look up the element very quickly. The capacity of a hash table is the number of elements the hash table can hold. As elements are added to a hash table, the capacity is automatically increased as required through reallocation. It is an older .Net Framework type.
Declaring a Hashtable: The Hashtable class is generally found in the namespace called System.Collections. So to execute any of the examples, we have to add using System.Collections; to the source code. The declaration for the Hashtable is:
Hashtable HT = new Hashtable ();
### Question : What is LINQ in C#?
LINQ stands for Language Integrated Query. LINQ is a data querying methodology which provides querying capabilities to .NET languages with syntax similar to a SQL query
LINQ has a great power of querying on any source of data. The data source could be collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable interface.
Advantages of LINQ:
• LINQ offers an object-based, language-integrated way to query over data no matter where that data came from. So through LINQ we can query database, XML as well as collections.
• Compile time syntax checking.
• It allows you to query collections like arrays, enumerable classes etc. in the native language of your application, and like VB or C# in much the same way as you would 66 query a database using SQL.
### Question : What is File Handling in C#.Net?
The System.IO namespace provides four classes that allow you to manipulate individual files, as well as interact with a machine directory structure. The Directory and File directly extends System.Object and supports the creation, copying, moving and deletion of files using various static methods. They only contain static methods and are never instantiated. The FileInfo and DirecotryInfo types are derived from the abstract class FileSystemInfo type and they are typically, employed for obtaining the full details of a file or directory because their members tend to return strongly typed objects. They implement roughly the same public methods as a Directory and a File but they are stateful and the members of these classes are not static.
### Question : What is Reflection in C#.Net?
Reflection typically is the process of runtime type discovery to inspect metadata, CIL code, late binding and self-generating code. At run time by using reflection, we can access the same "type" information as displayed by the ildasm utility at design time. The reflection is analogous to reverse engineering in which we can break an existing *.exe or *.dll assembly to explore defined significant contents information, including methods, fields, events and properties.
You can dynamically discover the set of interfaces supported by a given type using the System.Reflection namespace. This namespace contains numerous related types as follows:
Types
Description
Assembly
this static class allows you to load,investigate and manipulate an assembly
Assemblyname
allows to exploration of adundant details behind an assembly
Eventinfo
information about a given event
Propertyinfo
hold information of a specified property
Methodinfo
contains information about a specified method
Reflection typically is used to dump out the loaded assemblies list, their reference to inspect methods, properties etcetera.
Reflection is also used in the external disassembling tools such Reflector, Fxcop and NUnit because .NET tools don't need to parse the source code similar to C++.
Metadata Investigation:
The following program depicts the process of reflection by creating a console based application. This program will display the details of the fields, methods, properties and interfaces for any type within the mscorlib.dll assembly. Before proceeding, it is mandatory to import "System.Reflection".
Here, we are defining a number of static methods in the program class to enumerate fields, methods and interfaces in the specified type. The static method takes a single "System.Type" parameter and returns void.
static void FieldInvestigation(Type t) {
Console.WriteLine("*********Fields*********");
FieldInfo[] fld = t.GetFields();
foreach(FieldInfo f in fld) { Console.WriteLine("-->{0}", f.Name); } }
static void MethodInvestigation(Type t) {
Console.WriteLine("*********Methods*********");
MethodInfo[] mth = t.GetMethods();
foreach(MethodInfo m in mth) { Console.WriteLine("-->{0}", m.Name); } }
### Question : What is Expression Trees In C#?
Expression and Expression<> are basically classes that can represent the CSharp code as Data. Unlike Func<> or Action<> Expressions are non-compiled Data about the code. Most of LINQ Providers has been built using Expressions.
Walkthrough of a