How you can explain String ???
How you can explain String ???
More interview questions and answers |
---|
Single Class can be separated into multiple physical files with same logical name. |
a |
Code which execute on client are called client side code Otherwise Server side code. |
Give Real life examples of polymorphisms, encapsulation and inheritance? |
real lif example of inheritance is parent child relationship |
Partial Class: when a class need to be implemented at multiple locations with same class name then those classes need to be declared as "partial". Example: public main() { class Test { ------- ------- } class Test //error { ------- ------- } } public main() { partial class Test { ------- ------- } partial class Test //correct { ------- ------- } } |
csc |
Object:-Object is the basic run time entity. The object type is based on System.Object in the .NET Framework. You can assign values of any type to variables of type object. All data types, predefined and user-defined, inherit from the System.Object class. The object data type is the type to and from which objects are boxed. Exapmle:- class a {} public static void Main() { a ob= new a();// create object ob of class a; } |
Class:- Classes are declared using the keyword class. The declaration takes the form: [attributes] [modifiers] class identifier [:base-list] { class-body }[;] where: attributes (Optional) :-Additional declarative information. modifiers (Optional):- The allowed modifiers are new, abstract, sealed, and the four access modifiers. identifier:- The class name. base-list (Optional) :-A list that contains the one base class and any implemented interfaces, all separated by commas. class-body :-Declarations of the class members. Example:- Public class a { // some members and parameter } |
what abstraction,encapsulation,inheritance? Define with example. |
Abstraction:-Abstraction is the process of hiding the details and exposing only the essential features of a particular concept or object. Abstraction is another good feature of OOPS. Abstraction means to show only the necessary details to the client of the object Example:-A simple example is using a base class "Animal", with a virtual function "Walk". In the case two-legged versus four-legged animals, both of them walk, but the actual mechanics are different. The "Walk" method abstracts the actual mechanics behind the walking that each "Animal" does. 2nd example:-A class called Animal. It has properties like ears,colour, eyes but they are not defined. It has methods like Running(), Eating(), etc. but the method does not have any body, just the definition. Encapsulation:-Encapsulation is the term given to the process of hiding all the details of an object that do not contribute to its essential characteristics.its wrapping of data and members in a single unit.Encapsulation is a process of hiding all the internal details of an object from the outside world . 1:- Encapsulation is the ability to hide its data and methods from outside the world and only expose data and methods that are required . 2.Encapsulation gives us maintainability, flexibility and extensibility to our code. 3.Encapsulation provides a way to protect data from accidental corruption . 4.Encapsulation gives you the ability to validate the values before the object user change or obtain the value . 5.Encapsulation allows us to create a "black box" and protects an objects internal state from corruption by its clients. 6.Encapsulation is the technique or process of making the fields in a class private and providing access to the fields using public methods. Example:-cars and owners... all the functions of cars are encapsulated with the owners.. No one else can access it... Inheritance:-In object-oriented programming (OOP), Inheritance is a way to compartmentalize and reuse code by creating collections of attributes and behaviors called objects which can be based on previously created objects. In classical inheritance where objects are defined by classes. classes can inherit other classes. The new classes, known as Sub-classes (or derived classes), inherit attributes and behavior of the pre-existing classes, which are referred to as Super-classes. the process of deriving one class from parent class called . Example:-INHERITANCE MEANS A CHILD CLASS USE THE ALL THE ELEMENTS IN THE PARENTS CLASS. DAD | CHILED Seccond Example:- Kingfisher jet ^ | Airplane ^ | Flying Things |
Death Diamond:-In object-oriented programming languages with multiple inheritance and knowledge organization, the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B, or C? For example a class Button may inherit from both classes Rectangle (for appearance) and Clickable (for functionality/input handling), and classes Rectangle and Clickable both inherit from the Object class. Now if the equals method is called for a Button object and there is no such method in the Button class but there is an overridden equals method in both Rectangle and Clickable, which method should be eventually called? ihis is called "Death of Diamond". Ex: Class a { } class b: a {} class c: a {} class d:b,c {} It is called the "diamond problem" because of the example of the class inheritance in this situation. In this example, class A is at the top, both B and C separately inherit to A, and D inherits both...... |
what is the main difference between delegate and an event in c#? |
Delegate:-A delegate is basically a reference to a method. A delegate can be passed like any other variable. This allows the method to be called anonymously, without calling the method directly. delegate declaration defines a reference type that can be used to encapsulate a method with a specific signature. A delegate instance encapsulates a static or an instance method. Delegates are roughly similar to function pointers in C++; however, delegates are type-safe and secure. The delegate declaration takes the form: [attributes] [modifiers] delegate result-type identifier ([formal-parameters]) Event:-An event in one program can be made available to other programs that target the .NET runtime. An event is a member that enables an object or class to provide notifications. Clients can attach executable code for events by supplying event handlers. Events are declared using event-declarations: event-declaration: event-field-declaration event-property-declaration event-modifier: new public protected internal private static Example:- public delegate void EventHandler(object sender, Event e); public class Button: Control { public event EventHandler Click; protected void OnClick(Event e) { if (Click != null) Click(this, e); } public void Reset() { Click = null; } } |
How to use Hash Table,ArrayList in c# ?Explain with example. |
ArrayList:-Arraylist is a collection of objects(may be of different types). Arraylist is very much similar to array but it can take values of different datatypes. If you want to find something in a arraylist you have to go through each value in arraylist, theres no faster way out.ArrayList's size can be changed dynamically. Items are added to the ArrayList with the Add() method. example:-HOW TO ADD DATA IN ARRAYLIST: using System.Collections; class Program { static void Main() { // // Create an ArrayList and add three elements. // ArrayList list = new ArrayList(); list.Add("One"); list.Add("Two"); list.Add("Three"); } } EXAMPLE-Adding one ArrayList to second one There are different ways to add one ArrayList to another, but the best way is using AddRange. Internally, AddRange uses the Array.Copy or CopyTo methods, which have better performance than some loops. === Program that uses Add and AddRange === using System; using System.Collections; class Program { static void Main() { // // Create an ArrayList with two values. // ArrayList list = new ArrayList(); list.Add(15); list.Add(17); // // Second ArrayList. // ArrayList list2 = new ArrayList(); list2.Add(110); list2.Add(113); // // Add second ArrayList to first. // list.AddRange(list2); // // Display the values. // foreach (int i in list) { Console.WriteLine(i); } } } === Output of the program === 15 17 110 113 The ArrayList class provides the Count property, which is a virtual property. When you use Count, no counting is actually done; instead, a cached field value is returned HASH TABLE:-Hashtable is also collection which takes a key corresponding to each values. If you want to find something in a hashtable you dont have to go through each value in hashtable, instead search for key values and is faster.The Hashtable lets you quickly get an object out of the collection by using it's key. The Hashtable object contains items in key/value pairs. The keys are used as indexes. We can search value by using their corresponding key. The data type of Hashtable is object and the default size of a Hashtable is 16. Items are added to the Hashtable with the ADD()method. Example-How to add data in hash table:-- Add method of Hashtable is used to add items to the hashtable. The method has index and value parameters. The following code adds three items to hashtable. hshTable .Add("A1", "Kamal"); hshTable .Add("A2", "Aditya"); hshTable .Add("A3", "Ashish"); Retrieving an Item Value from Hashtable The following code returns the value of "Author1" key: string name = hshTable["A1"].ToString(); Removing Items from a Hashtable The Remove method removes an item from a Hashtable. The following code removes item with index "A1" from the hashtable: hshTable.Remove("A1"); Looking through all Items of a Hashtable The following code loops through all items of a hashtable and reads the values. // Loop through all items of a Hashtable IDictionaryEnumerator en = hshTable.GetEnumerator(); while (en.MoveNext()) { string str = en.Value.ToString(); } |
Difference between shadow and override:- Shadowing hide the inherrited method using new keyword and CLR choose the target mthod between the parent and child to call using the object's runtime type.Overriding hide the inherrited method using override keyword and the parent should be virtual. overrding always choose the object's compile-time type. Differences:- 1-PorPose:- SHADOW-Protecting against a subsequent base class modification introducing a member you have already defined in your derived class. OVERRIDE-Achieving polymorphism by defining a different implementation of a procedure or property with the same calling sequence 2-Redefined element:- SHADOW:-Any declared element type. OVERRIDE:-Only a procedure (Function or Sub) or property 3-Accessibility:- SHADOW:-Any accessibility OVERRIDE:-Cannot expand the accessibility of overridden element (for example cannot override Protected with Public) 4-Readability and writability SHADOW:-Any combination OVERRIDE:-Cannot change readability or writability of overridden property 5-Keyword usage SHADOW:-Shadows recommended in derived class; Shadows assumed if neither Shadows nor Overrides specified. OVERRIDE:-Overridable required in base class; Overrides required in derived class |
System.Object |
Classes in the same namespace. |
No directly,but we can use interface for multiple inheritence |
Place a colon and then the name of the base class. exmple:- class a {} class b: a //inherit class a {} |
Abstract class:-Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Abstract classes have the following features: 1-An abstract class cannot be instantiated. 2-An abstract class may contain abstract methods and accessors. 3-It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited. 4-A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors. Abstract class have complete and non complete member and methods. Example:- abstract class a { int a; public abstract void print(); } |
What does the keyword virtual mean in the method definition? |
It means that the subclasses( inheriting classes) can override the method. |
Difference between overriding and overloading:- 1:-When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class. 2:-overriding keyword cahnge behavour in derive class with same signature Overloading means same name but passing different datatype or different number arguments within the same class 3:-Method overloading means same method name but different parameters. Method overriding means same method name and parameters also same. In method overloading method will differentiate with parameters name and in method overriding method will differentiate with method signature |
protected internal:-Access is limited to the current project or types derived from the containing class.Access limited to the current project. |
Yes, but they are not accessible |
When you inherit a protected class-level variable? Who is it available to? |
Protected members can be accessible by all the derived class irrespective of the Namespaces only protected Friend or protected internal will be accessed inside the namespace |
What's the implicit name of the parameter that gets passed into the class' set method? |
Value, and its datatype depends on whatever variable we're changing |
yes,It is mandatory to implement all the methods which are there in abstract class if we inherit that abstract class? |
The difference is that static read-only can be modified by the containing class, but const can never be modified and must be initialized to a compile time constant. To expand on the static read-only case . The Constant Fields are those which cannot be changed in runtime. Its value has to be assigned at declaration time. const string strMyString="Constant Data" ; //This is valid.Once declared now the value cannot be reassigned strMyString="Changed Data" ... |
How to fill datalist usinf XML file and how to bind it,code behind language is c# ? |
SERIALIZATION:-serialization is the process of maintaing object in the form stream.it is useful in case of remoting. 2.Serialization is the process of converting object into byte stream which is useful to transport object(i.e remoting) persisting object(i.e files database) 3.SERIALIZATION IS PROCESS OF LODING THE OBJECT STATE IN THE FORM OF BYTE STREAMS IN DATABASE/FILE SYATEM. 4.Serialization in .NET allows the programmer to take an instance of an object and convert it into a format that is easily transmittable over the network or even stored in a database or file system. This object will actually be an instance of a custom type including any properties or fields you may have set 5.using Serialization instead of DataInput/DataOutput streams has a major impact on versioning . Serialization keeps a lot of metadata in the stream. This makes detecting format changes very easy, but can really complicate backward compatibility.Also,serialization is geared toward preserving the connections of an object graph, which is behind a lot of the differences you mentioned. |
SqlExceptionclass is created whenever the .NET Framework Data Provider for SQL Server encounters an error generated from the server. (Client side errors are thrown as standard common language runtime exceptions.) SqlException always contains at least one instance of SqlError. ... try { myCommand.Connection.Open(); } catch (SqlException e) { string errorMessages ; for (int i 0; i < e.Errors.Count; i++) { errorMessages + Index # + i + \n + Message: + e.Errors[i].Message + \n + LineNumber: + e.Errors[i].LineNumber + \n + Source: + e.Errors[i].Source + \n + Procedure: + e.Errors[i].Procedure + \n ; } System.Diagnostics.EventLog log new System.Diagnostics.EventLog(); log.Source My Application ; log.WriteEntry(errorMessages); Console.WriteLine( An exception occurred. Please contact your system administrator. ); } |
SqlExceptionclass is created whenever the .NET Framework Data Provider for SQL Server encounters an error generated from the server. (Client side errors are thrown as standard common language runtime exceptions.) SqlException always contains at least one instance of SqlError. |
Indexer:-Indexers permit instances of a class or struct to be indexed in the same way as arrays. Indexers are similar to properties except that their accessor take parameters. Indexers allow you to index a class or a struct instance in the same way as an array. To declare an indexer, use the following declaration: [attributes] [modifiers] indexer-declarator {accessor-declarations} The indexer-declarator takes one of the forms: type this [formal-index-parameter-list] type interface-type.this [formal-index-parameter-list] The formal-index-parameter takes the form: [attributes] type identifier where: attributes (Optional) :- Additional declarative information. For more information on attributes and attribute classes, modifiers (Optional) :- Allowed modifiers are new and a valid combination of the four access modifiers. indexer-declarator :- Includes the type of the element introduced by the indexer, this, and the formal-index-parameter-list. If the indexer is an explicit interface member implementation, the interface-type is included. formal-index-parameter-list:- Specifies the parameters of the indexer. The parameter includes optional attributes, the index type, and the index identifier. At least one parameter must be specified. The parameters out and ref are not allowed. accessor-declarations :- The indexer accessors, which specify the executable statements associated with reading and writing indexer elements. The get Accessor:- The get accessor body of an indexer is similar to a method body. It returns the type of the indexer. The get accessor uses the same formal-index-parameter-list as the indexer. For example: get { return myArray[index]; } The set Accessor:- The set accessor body of an indexer is similar to a method body. It uses the same formal-index-parameter-list as the indexer, in addition to the value implicit parameter. For example: set { myArray[index] = value; } |
indexer member, which itself contains a get accessor and a set accessor. These accessors are implicitly used when you assign the class instance elements in the same way as you can assign elements in an array. The indexer provides a level of indirection where you can insert bounds-checking, and in this way you can improve reliability and simplicity with indexers. |
yes,with the help of .dll of java class we can inherit the java class in c# |
every statement in c sharp must end with semi colon.it indicates statement completed |
C# code files have .cs exrension. |
We can compile a c# program using command promt such as :-csc filename |
yes. ASP .NET web pages can be programmed in C# |
All the .NET languages have the following in common 1-Base class library |
Il compiles to native code |
Which is the first level of compilation in the .NET languages? |
The first level of compilation in the .NET languages is source code convert into msil(Microsoft Intermediate language code which is generated by the C# compiler |
IL:-stands for Intermediate Language.This is the language code generated by the C# compiler or any .NET-aware compiler. All .NET languages generate this code. This is the code that is executed during runtime.You can view this MSIL code with the help of a utility called Intermediate Language Disassembler (ILDASM). This utility displays the application's information in a tree-like fashion. Because the contents of this file are read-only, a programmer or anybody accessing these files cannot make any modifications to the output generated by the source code. |
CTS:-CTS stands for Common Type System. 1-Common Type System is also a standard like cls. If two languages (c# or vb.net or j# or vc++) wants to communicate with each other, they have to convert into some common type (i.e in clr common language run time). In c# we use int which is converted to Int32 of CLR to communicate with vb.net which uses Integer or vice versa. 2-The Common Type System defines how types are declared, used, and managed in the runtime, and is also an important part of the runtime's support for cross-language integration. 3.The CTS makes available a common set of data types so that compiled code of one language could easily interoperate with compiled code of another language by understanding each others’ data types. |
System.Reflection is used for Reflection |
CSharp Collections are data structures that holds data in different ways for flexible operations . C# Collection classes are defined as part of the System.Collections or System.Collections.Generic namespace. Most collection classes implement the same interfaces, and these interfaces may be inherited to create new collection classes that fit more specialized data storage needs. collections are:- 1-C# ArrayList Class 2-Hash Table 3-Stack 4-Queue etc |
System.GC.Collect() |
Each process in a 32 bit Windows environment has the what amount of virtual memory will available? |
Correct syntax for defining a delegate:- [attributes] [modifiers] delegate result-type identifier ([formal-parameters]); where: attributes (Optional):- Additional declarative information. For more information on attributes and attribute classes, modifiers (Optional) :- The allowed modifiers are new and the four access modifiers. result-type :- The result type, which matches the return type of the method. identifier :- The delegate name. formal-parameters (Optional):- Parameter list. Example:- public delegate int delsum(int x,int y); |
Syntax of inherit a class:- Public class a { // some member and methods } class b:a // b class inherit a class { } |
Assembly:-There are several ways to deploy an assembly into the global assembly cache: 1) Use an installer designed to work with the global assembly cache. This is the preferred option for installing assemblies into the global assembly cache. 2) Use a developer tool called the Global Assembly Cache tool (Gacutil.exe)provided by the .NET Framework SDK. 3) Use Windows Explorer to drag and drop assemblies into the cache. |
The System.Globalization namespace holds all culture and region classes to support different date formats, different number formats, and even different calendars that are represented in classes such as GregorianCalendar, HebrewCalendar, JapaneseCalendar, and so on. By using these classes, you can display different representations depending on the user’s locale. |
If a running application does need to communicate or share data with other application running in different application domains,it must do by calling by on .NETs Remoting Services |
If we have an event handler called MyEvent and we want to link the click event of control, MyButton, to use MyEvent, Then code will be:- control.Click += new EventHandler(MyEvent); |
Which debugging window allows you to see the methods called in the order they were called? |
The Call Stack window allows you to see the methods called in the order they were called. |
The Call Stack window allows you to see all the name and values of all the variables in scope |
Wrapper class:-Wrapper class are those class in which we cant define and call all predefined functiuon.Wrapper Classes are the classes that wrap up the primitive values in to a class that offer utility method to access it . For eg you can store list of int values in a vector class and access the class. Also the methods are static and hence you can use them without creating an instance . The values are immutable . |
Protected Internal:-Access is limited to the current project or types derived from the containing class. 2-The item is visible to any code within its containing assembly and also to any code inside a derived type |
Which keyword is used of specify a class that cannot inherit by other class? |
By using "Sealed " keyword |
NO,we cant create the instance for absract classes |
no ,we can not use friend classes or function in c# |
How we can use inheritance and polymorphisms in c# programming? |
To find Exceptions in database:-Framework is endowed with provider specific exception class that we can use to handle exceptions from database. For example instance to handle exceptions from sqlserver we can use System.Data.SqlClient.SqlException class. |
Using Late Bound COM Objects |
Supporting .Net, because DLL made in C#.Net semi compiled version. It’s not a com object. It is used only in .Net Framework As it is to be compiled at runtime to byte code. |
There are following data types that support Range validator control:- 1-Integer 2-Date 3-String 4-Double 5-Currency |
Constructor is the method which is implicitly created when ever a class is instantiated. Why? |
The default constructor is called automatically when ever a class is instantiated. |
multiple inheritance is possible through interface |
In .NET, strings are immutable. This means that, once a value is assigned to a String object, it can never be changed. |
C# equivalent is : System.Text.RegularExpressions.Regex myRegex new Regex (" ( ([^""]*""[^""]*"")*(?![^""]*""))"); |
use the aximp.exe provided with the .NET framework. It stands for Microsoft .NET ActiveX Control to Windows Forms Assembly Generator. Generates a Windows Forms Control that wraps ActiveX controls defined in the OcxName. |
What is the main difference between pointer and delegate with examples? |
The difference between pointer and delegate:- Delegate:-A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure. Example:- using System; delegate void MyDelegate(string s); class MyClass { public static void Hello(string s) { Console.WriteLine(" Hello, {0}!", s); } public static void Goodbye(string s) { Console.WriteLine(" Goodbye, {0}!", s); } public static void Main() { MyDelegate a, b, c, d; a = new MyDelegate(Hello); b = new MyDelegate(Goodbye); c = a + b; // Compose two delegates to make another d = c - a; // Remove a from the composed delegate Console.WriteLine("Invoking delegate a:"); a("A"); Console.WriteLine("Invoking delegate b:"); b("B"); Console.WriteLine("Invoking delegate c:"); c("C"); Console.WriteLine("Invoking delegate d:"); d("D"); } } Output Invoking delegate a: Hello, A! Invoking delegate b: Goodbye, B! Invoking delegate c: Hello, C! Goodbye, C! Invoking delegate d: Goodbye, D! Code Discussion Pointer:-C# statements execute in either a safe or an unsafe context. Safe context is the default, but any code using pointers requires unsafe context. unsafe:- Specifies unsafe context. Once you have a pointer to a variable, you must ensure that the variable isn't moved in memory by the garbage collector. pointer holds reference to a variable or pointer is a variable which holds the address of another variable. Example:- using System; class UnsafeTest { // unsafe method: takes pointer to int unsafe static void SquarePtrParam (int* p) { *p *= *p; } public static void Main() { int i = 5; // unsafe statement for address-of operator unsafe SquarePtrParam (&i); Console.WriteLine (i); } } Output 25 |
Object pooling :- Object pooling is a COM+ Service that enables to reduce the overhead of creating each object from scratch, Object pooling is a well known technique to minimize the creation of objects that can take a significant amount of time. Common examples are to create a pool of database connections such that each request to the database can reuse an existing connection instead of creating one per client request.Threads are also another common candidate for pooling in order to increase responsiveness of an application to multiple concurrent client requests. |
connection cn=System.Configuration.ConfigurationManeger.Appsetting(variable name) in 2005 |
C# does not support optional arguments. |
XML Schema:-The aim of an XML Schema is to define the legal building blocks of an XML document, just like a DTD.XML Schema is an XML-based alternative to DTD.An XML schema describes the structure of an XML document.The XML Schema language is also referred to as XML Schema Definition (XSD). XML Schema defines elements that can appear in a document. XML Schema defines attributes that can appear in a document XML Schema defines which elements are child elements XML Schema defines the order of child elements XML Schema defines the number of child elements XML Schema defines whether an element is empty or can include text XML Schema defines data types for elements and attributes. XML Schema defines default and fixed values for elements and attributes |
How can we check whether a dataset is empty or not in C#.net |
To check whether a dataset is empty or not in C#.net:- bool IsEmpty(DataSet dataSet) { foreach(DataTable table in dataSet.Tables) if (table.Rows.Count != 0) return false; return true; } |
Is it possible to inherit a class that has only private constructor? |
No,Its not possible to inherit a class that has only private constructor. |
How do you choose 1 entry point when C# project has more Main( ) method? |
If project has more Main()method:- CSC /main:classname filename.cs |
Keyword:-C# has a number of built in keywords. Keywords are predefined reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include @ as a prefix. List of Reserved Keyword:- abstract, enum ,long, stackalloc , as, event ,namespace ,static, base ,explicit, new, string, bool, extern ,null, struct, break ,false ,object, switch, byte, finally, operator, this, case, fixed, out, throw, catch, float, override ,true char ,for, params ,try , checked ,foreach, private, typeof, class, goto ,protected ,uint, const, if, public ,ulong, continue, implicit ,readonly, unchecked, decimal ,in ,ref, unsafe , default, int ,return ,ushort, delegate ,interface ,sbyte, using do, internal, sealed ,virtual double ,is, short, void else ,lock ,sizeof, while |
NO,Sealed classes cant be inherited |
It is not permitted to declare modifier on the members in an interface definition? |
yes.It is not permitted to declare modifier on the members in an interface definition. By default all the members in an Interface definition are public so there is no need to declare access modifier public. It would be a compile time error otherwise |
Interface:-The interface keyword declares a reference type that has abstract members. The interface declaration takes the form: [attributes] [modifiers] interface identifier [:base-list] {interface-body}[;] where: attributes (Optional):- Additional declarative information. modifiers (Optional) :- The allowed modifiers are new and the four access modifiers. identifier :- The interface name. base-list (Optional) :- A list that contains one or more explicit base interfaces separated by commas. interface-body :- Declarations of the interface members. example:- public interface A { void show(string s); } public interface b { void get(string s); } class d: a,b { } |
Which method is implicitly called when an object is created ? |
constructor will call when an object is created |
NO,Constructors can be static. |
Attributes:-Attributes are elements that allow you to add declarative information to your programs. This declarative information is used for various purposes during runtime and can be used at design time by application development tools. Attributes are generally applied physically in front of type and type member declarations. They're declared with square brackets, "[" and "]", surrounding the attribute such as the following ObsoleteAttribute attribute: |
For performing repeated modification on string which class is preferred? |
String.Builder |
In order to use stringbuilder in our class we need to refer?? |
using System.Text; |
Which method is actually called ultimately when Console.WriteLine( ) is invoked? |
AppendFormat() method is actually called ultimately when Console.WriteLine( ) is invoked? |
What happens when you create an arraylist as ArrayList Arr=new ArrayList()? |
when you create an arraylist as ArrayList Arr=new ArrayList() then an arraylist of object Arr is created with the capacity of 16 |
The output of Vectors.RemoveAt(1):-Removes the object at position 1 |
GetEnumerator( ) of Ienumerable interface Returns an enumerator that iterates through a collection. |
With the help of ADD()method we can add objects to hashtablein c# |
If A.equals(B) is true then A.getHashcode & B.getHashCode must always return same hash code in c#? |
Flase because it is given that A.equals(B) returns true i.e. objects are equal and now its hashCode is asked which is always independent of the fact that whether objects are equal or not. So, GetHashCode for both of the objects returns different value. |
The assembly class is defined inSystem.Reflection. |
It forms a security boundary and then reference boundary |
By using Assembly.Load( )and Assembly.LoadFrom( ) we can loadssembly to running process |
True.Assemblies cannot be loaded side by side. |
Application Isolation is assured using:- Load assembly to running process |
ApplicationDomain |
base keyword is used |
STAthread stands for Single Thread Application |
We can make a class not instantiable by making abstract class. |
In a multilevel hierarchy how are the constructors are called ?? |
Resgen.exe |
A shared assembly must have a strong name to uniquely identify the assembly?? |
System.IO |
File Strem and Memory Sream |
Which method is used by COM+ to ascertain whether class can be pooled?? |
.Net Remoting doesn't allow creating stateless & stateful Remote objects?Explain. |
What is the order of destructors called in a polymorphism hierarchy ?? |
How can you sort the elements of the array in descending order?? |
NO,Its not possible to override private virtual method |
with the help of // we can single line comments |
Explain How ?Intermediate Language also facilitates language interoperability. |
NET interfaces are not derived from IUnknown & they do not have associated GUID's? |
Is it possible to debug the class written in other .Net languages in a C# project. |
yes.It is possible to debug the class written in other .net language in a c# project.since .net can combine code written in several .net languages into one single assembly. Same is true with debugging. |
.NET run time relies on the object reference counts to manage memory? |
What are basic need to have an entry point of an apllication?? |
Main method returns both type.int and void |
What happens if we refer a variable which in not initialized in C# ? |
If you need your own implementation of Equals method of object what needs ? |
Which modifiers hides an inherited method with same signature?? |
How do you check whether an Object is compatible with Specific Type ? |
How do you determine the size required by a Value type on the stack?? |
What happens when a C# project has more than one Main methods?? |
The field variables in a class or a struct in C# are by default given a value of zero ?? |
Which tool is used to browse the classes, structs, interfaces etc. in the BCL? |
WinCV |
IF a namespace isn't supplied then which namespace does a class belong to System? |
Does C# collection allows accessing an element using a unique key? |
Does finally block will execute? Even if an exception hasn't occurred. |
yes |
How Interfaces provide implementation of methods ?Explain with a example. |
To change the value of a variable while debugging , What you need to do? |
Are there some features of C# language not supported by .NET?If yes List features. |
Can any process be divided into multiple process? If Yes then how? |
Can applications running in different Application Domains communicate with each other? |
How we can register a private assembly in the Windows registry? |
It is available to any sub-class (a class inheriting this class). |
Describe the accessibility modifier �protected internal�. |
What�s the top .NET class that everything is derived from? |
What�s the difference between System.String and System.Text.StringBuilder classes? |
What�s the advantage of using System.Text.StringBuilder over System.String? |
What�s the difference between the System.Array.CopyTo() and System.Array.Clone()? |
How can you sort the elements of the array in descending order? |
What�s the .NET collection class that allows an element to be accessed using a unique key? |
Will the finally block get executed if an exception has not occurred? |
Can multiple catch blocks be executed for a single try statement? |
Explain the three services model commonly know as a three-tier application. |
Can you prevent your class from being inherited by another class? |
Can you allow a class to be inherited, but prevent the method from being overridden? |
Why can�t you specify the accessibility modifier for methods inside the interface? |
What happens if you inherit multiple interfaces and they have conflicting method names? |
What�s the difference between an interface and abstract class? |
What does the keyword �virtual� declare for a method or property? |
Can you declare an override method to be static if the original method is not static? |
What�s the difference between // comments, /* */ comments and /// comments? |
How do you generate documentation from the C# file commented properly with a command-line compiler? |
What�s the difference between the Debug class and Trace class? |
Why are there five tracing levels in System.Diagnostics.TraceSwitcher? |
What are three test cases you should go through in unit testing? |
Can you change the value of a variable while debugging a C# application? |
What is the role of the DataReader class in ADO.NET connections? |
What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? |
What does the Initial Catalog parameter define in the connection string? |
server name |
What namespaces are necessary to create a localized application? |
What is the difference between a static and an instance constructor? |
You have one base class virtual function how will you call the function from derived class? |
What is Method Overriding? How to override a function in C#? |
What happens if we inherit multiple interfaces and there is conflicting method names? |
Why can we not specify the accessibility modifier for methods inside the interface? |
Yes..but don't frm multilevel |
What is the order of destructor called in a polymorphism hierarchy? |
No |
Can you declare a C++ type destructor in C# like ~ClassName()? |
Namespace |
If A.equals(B) is true then A.getHashcode & B.gethashcode must always return same hash code. |
Is it possible to debug the classes written in other .Net languages in a C# project? |
Yes |
IS it possible to have different access modifiers on the get/set methods of a property? |
Is there an equivalent of exit() or quiting a C#.NET application? |
yes |
What optimization does the C# compiler perform when you use the optimize & compiler option? |
NO |
What happens when you encounter a continue statement inside for loop? |
loop will execute |
Write one code example for compile time binding and one for run time binding. |
class |
QUESTION:-What’s the advantage of using System.Text.StringBuilder over |
What’s the advantage of using System.Text.StringBuilder over ? |
StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created. |
Question:-What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? |
System.Array.CopyTo() performs a deep copy of the array, the System.Array.Clone is shallow. |
Question:-How can you sort the elements of the array in descending order? |
we can sort the elements of the array in descending order By calling Sort() and then Reverse() methods. |
No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block. |
A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers. |
Multicast delegate is a delegate that points to and eventually fires off several methods. |
Since Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly. |
Satellite Assembly:-When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies. |
What namespaces are necessary to create a localized application? |
The Namespace are necessary to create a localized application is System.Globalization, System.Resources. |
What’s the difference between // comments, /* */ comments and /// comments |
// comments means Single-line comments , /* */ comments means multi-line and /// comments means XML documentation comments. |
How do you generate documentation from the C# file commented properly with a command-line compiler? |
For generate documentation from the C# file commented properly with a command-line compile:- Compile it with a /doc switch. |
What’s the difference between the Debug class and Trace class? Documentation looks the same |
Debug class is Used for debug builds,and Trace class used for both debug and release builds. |
Why are there five tracing levels in System.Diagnostics.TraceSwitcher? |
The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities. |
No, multiple catch blocks can not be executed. once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block. |
Is it possible to have different access modifiers on the get/set methods of a property? |
No. The access modifier on a property applies to both its get and set accessors. What you need to do if you want them to be different is make the property read-only (by only providing a get accessor) and create a private/internal set method that is separate from the property. |
C# (pronounced C-sharp) is a new object oriented language from Microsoft and is derived from C and C++. It also borrows a lot of concepts from Java too including garbage collection. |
Assemblies are the smallest units of versioning and deployment in the .NET application. Assemblies are also the building blocks for programs such as Web services, Windows services, serviced components, and .NET remoting applications. |
Private assembly is used inside an application only and does not have to be identified by a strong name. Shared assembly can be used by multiple applications and has to have a strong name. |
Strong Name:-A strong name includes the name of the assembly, version number, culture identity, and a public key token. |
shared assemblies stored in Global assembly cache. |
To create a strong name for a .NET assembly With the help of Strong Name tool (sn.exe). |
global assembly cache located on the system in C:\winnt\assembly or C:\windows\assembly. |
Yes, remember that GAC is a very special folder, and while normally you would not be able to place two files with the same name into a Windows folder, GAC differentiates by version number as well, so it’s possible for MyApp.dll and MyApp.dll to co-exist in GAC if the first one is version 1.0.0.0 and the second one is 1.1.0.0. |
You must use the Missing class and pass Missing.Value (in System.Reflection) for any values that have optional parameters. |
To make a Dll in C# we need to use the /target:library compiler option. |
Delay signing:-It allows you to place a shared assembly in the GAC by signing the assembly with just the public key. This allows the assembly to be signed with the private key at a later stage, when the development process is complete and the component or assembly is ready to be deployed. This process enables developers to work with shared assemblies as if they were strongly named, and it secures the private key of the signature from being accessed at different stages of development. |
Can you prevent your class from being inherited and becoming a base class for some other classes? |
Yes,we can prevent class from being inherited by using sealed class, keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class Whatever BaseClassName. It is the same concept as final class in Java. |
Will finally block get executed if the exception had not occurred? |
yes,finally block will get executed if the exception had not occurred |
Is there regular expression (regex) support available to C# developers? |
Yes. The .NET class libraries provide support for regular expressions. Look at the documentation for the System.Text.RegularExpressions namespace. |
yes,Yes. Set all references to null and then call System.GC.Collect(). If you need to have some objects destructed, and System.GC.Collect() doesn't seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers(). |
satellite assembly:-When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies. |
When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class. |
We do absolutely have to declare a class as abstract When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden. |
absolutely have to declare a class as abstract :- When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden. |
What is the implicit name of the parameter that gets passed into the class set method? |
The implicit name of he parameter that gets passed into the class set method is Value, and its datatype depends on whatever variable we are changing. |
Use the regasm.exe utility to generate a type library (if needed) and the necessary entries in the Windows Registry to make a class available to classic COM clients. Once a class is registered in the Windows Registry with regasm.exe, a COM client can use the class as though it were a COM class. |
Unfortunately, this is currently not supported in the IDE. To do this from the command line, you must compile your projects into netmodules (/target:module on the C# compiler), and then use the command line tool al.exe (alink) to link these netmodules together. |
Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there is no implementation in |
Why cannot you specify the accessibility modifier for methods inside the interface? |
Because They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it is public by default. |
Why do I get a syntax error when trying to declare a variable called checked? |
The word checked is a keyword in C#. |
What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development? |
using RegAsm.exe. The general syntax would be: RegAsm. A good description of RegAsm and its associated switches is located in the .NET SDK docs. Just search on "Assembly Registration Tool".Explain ACID rule of thumb for transactions. Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no in-between case where something has been updated and something hasnot), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after). |
The difference is that static read-only can be modified by the containing class, but const can never be modified and must be initialized to a compile time constant. To expand on the static read-only case a bit, the containing class can only modify it: -- in the variable declaration (through a variable initializer). -- in the static constructor (instance constructors if it's not static). |
What does the parameter Initial Catalog define inside Connection String? |
The database name to connect to. |
System,Object |
Can you allow class to be inherited, but prevent the method from being over-ridden? |
Yes, just leave the class public and make the method sealed |
Can you change the value of a variable while debugging a C# application? |
Yes, if you are debugging via Visual Studio.NET, just go to Immediate window. |
Yes, but they are not accessible. |
Yes. .NET does support multiple interfaces. |
How can I create a process that is running a supplied native executable (e.g., cmd.exe)? |
The following code should run the executable and wait for it to exit before continuing: using System; using System.Diagnostics; public class ProcessTest { public static void Main(string[] args) { Process p = Process.Start(args[0]); p.WaitForExit(); Console.WriteLine(args[0] + " exited."); } } Remember to add a reference to System.Diagnostics.dll when you compile. |
It is available to classes that are within the same assembly and derived from the specified base class. |
Immutable means the data value may not be changed. |
no,we cant store multiple data types in System.Array? |
What’s the .NET collection class that allows an element to be accessed using a unique key? |
Hash Table |
sorted HashTable. |
Explain the three services model commonly know as a three-tier application? |
these are:-Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources). |
Can you allow a class to be inherited, but prevent the method from being over-ridden? |
Just leave the class public and make the method sealed. |
Abstract Class:-A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation. |
.When do you absolutely have to declare a class as abstract? |
1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden. 2. When at least one of the methods in the class is abstract. |
Interface:-Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. |
What happens if you inherit multiple interfaces and they have conflicting method names? |
It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay. |
What’s the difference between an interface and abstract class? |
n an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers. |
Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that structs cannot inherit. |
What’s the implicit name of the parameter that gets passed into the set method/property of a class? |
Value. The data type of the value parameter is defined by whatever data type the property is declared . |
What does the keyword “virtual” declare for a method or property? |
The method or property can be overridden. |
Can you declare an override method to be static if the original method is not static? |
No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to keyword override) |
Different parameter data types, different number of parameters, different order of parameters. |
Delegate:-A delegate object encapsulates a reference to a method. |
A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called. |
What’s the implicit name of the parameter that gets passed into the class’ set method? |
Value, and it’s datatype depends on whatever variable we’re changing. |
Place a colon and then the name of the base class. |
When you inherit a protected class-level variable, who is it available to? |
Classes in the same namespace. |
It’s available to derived classes and classes within the same Assembly (and naturally from the base class it’s declared in). |
. What does the keyword virtual mean in the method definition? |
The method can be over-ridden. |
Can you declare the override method static while the original method is non-static? |
No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access. |
No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access. |
It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes. |
Yes, you can create custom events for your own objects and you can also create them for existing objects. Creating custom events, |
Is it possible for objects that don't have an interface to support events? |
Yes. To use the events of such an object, however, the object variable must be dimensioned a special way or the events aren't available. |
Absolutely. Visual C#'s context-sensitive Help extends to code as well as to visual objects. To get help on a member, write a code statement that includes the member (it doesn't have to be a complete statement), position the cursor within the member text, and press F1. For instance, to get help on the int data type, you could type int, position the cursor within the word int, and press F1. |
Params:-The params keyword is used to describe methods that can receive any number of parameters of the specified type, and it results in extra allocations and reduced performance but improves the flexibility of the calling patterns. The main use of the params keyword is to give the ability to create functions that take a variable number of arguments. Example:- Public int sumnumber(params int[] list) { int sum = 0; foreach (int i in list) sum += i; return sum; } Public static void Main() { int ans1 = sumnumber(1); int ans2 = sumnumber(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); int ans3 = sumnumber(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); int ans4 = sumnumber() } OUTPUT:- 1 55 55 0 |
OUT:-out keyword is used for passing a variable for output purpose. It has same concept as ref keyword, but passing a ref parameter needs variable to be initialized while out parameter is passed without initialized. It is useful when we want to return more than one value from the method. Example of “out keyword”: class Test { public static void Main() { int a; fun(out a); Console.WriteLine("The value of a is " + a); } public static void fun(out int i) { i=4; //must assigned value. } } The program will result : The value of a is 4 |
REF:-A reference type and sending a parameter by reference are two different things. If you send a reference type to a method (passed by value), then the reference is passed by value. Since you are sending a reference, you can still access the same object outside of the method using another variable set to the same reference. Now, if you pass that reference by ref, you can modify the value of that parameter so that it holds a new reference to a new object. When you pass it by value, you can't do that. Example:- Using System; class Color { public Color() { this.red = 255; this.green = 0; this.blue = 125; } protected int red; protected int green; protected int blue; public void Getscol(ref int red, ref int green, ref int blue) { red = this.red; green = this.green; blue = this.blue; } } class RefTest1App { public static void Main() { Color color = new Color(); int red; int green; int blue; color.Getscol(ref red, ref green, ref blue); Console.WriteLine("red = {0}, green = {1}, blue = {2}", red, green, blue); } } |
Delegate:- delegate is a type-safe object that can point to another method (or possibly multiple methods) in the application, which can be invoked at later time. when you want to create a delegate in C# you make use of delegate keyword. A delegate type maintains three important pices of information : 1. The name of the method on which it make calls. 2. Any argument (if any) of this method. 3. The return value (if any) of this method. signature of delegate:- Access modifier delegate returntype delegatename (passing value must be same as a function ); public delegate int DelegateName(int x, int y); Example:- namespace MyFirstDelegate { public delegate int MyDelegate(int x, int y); public class MyClass { public static int Add(int x, int y) { return x + y; } public static int Mul(int x, int y) { return x * y; } } class Program { static void Main(string[] args) { MyDelegate del1 = new MyDelegate(MyClass.Add); int addResult = del1(5, 5); Console.WriteLine("5 + 5 = {0}\n", addResult); MyDelegate del2 = new MyDelegate(MyClass.Mul); int multiplyResult = del2(5, 5); Console.WriteLine("5 X 5 = {0}", multiplyResult); Console.ReadLine(); } } } |
Features of delegates: * A delegate represents a class. * A delegate is type-safe. * We can use delegates both for static and instance methods * We can combine multiple delegates into a single delegate. * Delegates are often used in event-based programming, such as publish/subscribe. * We can use delegates in asynchronous-style programming. * We can define delegates inside or outside of classes. |
PROPERTY:-Properties provide the opportunity to protect a field in a class by reading and writing to it through the property it is a special method that can return a current object?s state or set it. Simple syntax of properties can see in the following example: public int Old { get {return m_old;} set {m_old = value;} } public string Name { get {return m_name;} Example:- public class prop { private int age; public int humanAge { get //get accessor method { return age; } set //set accessor method { age = value; } } } So when in main program(C#) user wants to use these set and get method to set and get person age. They will use it as Perop boyAge = new Perop(); //create instance of object boyAge. humanAge = 10; // set the age of boy by using setter method of object int bAge = boyAge. humanAge;// get the age of boy by // using getter method of object Console.WriteLine(" Boy age is {0}"+ bAge ); Class Perop is property holder class. In which humanAge is property implementation. value : In set method value variable is internal c# variable. User no needs to define it explicitly. |
Method Overloading:-A method is considered to be an overloaded method, if it has two or more signatures for the same method name. These methods will contain different parameters but the same return types.It become within the class. A simple example for an overloaded methods are: Public void sum(int a, params int[] varParam); Public void sum(int a); |
Partial Type:-C# 2.0 introduces the concept of a partial type declaration. This is quite simply a single type which spans multiple files, where each file declares the same type using the partial modifier. The files may refer to members declared within one another without problem (just as forward references within C# is already not a problem). Example:- 1st Part-- partial class Test { string name; static void Main() { Test t = new Test("C# 2.0"); t.SayHello(); } } 2ND PART:- using System; partial class Test { Test(string name) { this.name = name; } void SayHello() { Console.WriteLine ("Hi there. My name is {0}.", name); } Compile with: csc Test1.cs Test2.cs Results: Hi there. My name is C# 2.0. |
Aliases:-C# 2.0 introduces the concept of an "alias". This allows you to effectively name an assembly reference when you compile the code, and use that name to disambiguate between names. As well as disambiguating between identical namespace-qualified names, aliases allow you to disambiguate between names which have been declared within an already used namespace and names which belong to the "root" namespace. This is achieved with the predefined alias of global. Example:- using System; namespace Foo.Bar { public class Baz { public static void SayHiLib() { Console.WriteLine ("Hello Lib"); } } } Baz.cs: using System; namespace Foo.Bar { public class Baz { public static void SayHiNested() { Console.WriteLine ("Hello Nested"); } } } class Baz { public static void SayHiBaz() { Console.WriteLine ("Hello Baz"); } } Test.cs: extern alias X; namespace Foo.Bar { class Test { public static void Main() { Baz.SayHiNested(); global::Baz.SayHiBaz(); X::Foo.Bar.Baz.SayHiLib(); } } } Compile: csc /target:library Lib.cs csc /r:X=lib.dll Baz.cs Test.cs |
Static Class:-These are simply declared using the static modifier. They cannot be derived from or instantiated, and they have no constructors . Their members must all be static. Example:- using System; public static class staticexample { public static void Foo() { Console.WriteLine ("Hello"); } } // Uncommenting this creates a compile-time error, // as static classes can't be derived from // public class DerivationAttempt :staticexample{} class Test { static void Main() { staticexample.Foo(); } } |
Method:-Method is object-oriented item of any language. All C# programs are constructed from a number of classes and almost all the classes will contain methods. A class when instantiated is called an object. Object-oriented concepts of programming say that the data members of each object represent its state and methods represent the object behavior. Method Signature:- Each method is declared as follows: Access modifier Return-type methodname ( Parameterslist ); Example:- public string printpro(string s,int y); |
Indexer:- * Indexer Concept is object act as an array. * Indexer an object to be indexed in the same way as an array. * Indexer modifier can be private, public, protected or internal. * The return type can be any valid C# types. * Indexers in C# must have at least one parameter. Else the compiler will generate a compilation error. Signature:- his [Parameter] { get { // Get codes goes here } set { // Set codes goes here } } ................................................. Exapmle:- using System; using System.Collections.Generic; using System.Text; namespace Indexers { class PClass { private string[] range = new string[5]; public string this[int indexrange] { get { return range[indexrange]; } set { range[indexrange] = value; } } } /* The Above Class just act as array declaration using this pointer */ class cclass { public static void Main() { PClass obj = new PClass(); obj[0] = "ONE"; obj[1] = "TWO"; obj[2] = "THREE"; obj[3] = "FOUR "; obj[4] = "FIVE"; Console.WriteLine("WELCOME TO C# CORNER HOME PAGE\n"); Console.WriteLine("\n"); Console.WriteLine("{0}\n,{1}\n,{2}\n,{3}\n,{4}\n", obj[0], obj[1], obj[2], obj[3], obj[4]); Console.WriteLine("\n"); Console.WriteLine("ALS.Senthur Ganesh Ram Kumar\n"); Console.WriteLine("\n"); Console.ReadLine(); } } } |
Event:-The Event model in C# finds its roots in the event programming model that is popular in asynchronous programming. The basic foundation behind this programming model is the idea of "publisher and subscribers." Example:- using System; using System.IO; namespace EventExample { public class MyClass { public delegate void LHandler(string message); // Define an Event based on the above Delegate public event LHandler Log; // Instead of having the Process() function take a delegate // as a parameter, we've declared a Log event. Call the Event, public void Process() { OnLog("Process() begin"); OnLog("Process() end"); } protected void OnLog(string message) { if (Log != null) { Log(message); } } } // The FLog class merely encapsulates the file I/O public class FLog { FileStream fileStream; StreamWriter streamWriter; // Constructor public FLog(string filename) { fileStream = new FileStream(filename, FileMode.Create); streamWriter = new StreamWriter(fileStream); } // Member Function which is used in the Delegate public void Logger(string s) { streamWriter.WriteLine(s); } public void Close() { streamWriter.Close(); fileStream.Close(); } } public class TestApplication { static void Logger(string s) { Console.WriteLine(s); } static void Main(string[] args) { FLog fl = new FLog("process.log"); MyClass myClass = new MyClass(); // Subscribe the Functions Logger and fl.Logger myClass.Log += new MyClass.LHandler(Logger); myClass.Log += new MyClass.LHandler(fl.Logger); // The Event will now be triggered in the Process() Method myClass.Process(); fl.Close(); } } } Compile an test: # csc EventExample.cs # EventExapmle.exe Process() begin Process() end # cat process.log Process() begin Process() end An event is a placeholder for code that is executed when the event is triggered, or fired. Events are fired by a user action, program code, or by the system. The following important conventions are used with events: * Event Handlers in the .NET Framework return void and take two parameters. * The first paramter is the source of the event; that is the publishing object. * The second parameter is an object derived from EventArgs. * Events are properties of the class publishing the event. * The keyword event controls how the event property is accessed by the subscribing classes. |
Exception Handling:-# provides built-in support for handling anomalous situations, known as exceptions, which may occur during the execution of your program. These exceptions are handled by code that is outside the normal flow of control. The try, throw, catch, and finally keywords implement exception handling. Throw:-The throw statement is used to signal the occurrence of an anomalous situation (exception) during the program execution. The throw statement takes the form: throw [expression]; where: expression :- The exception object. This is omitted when re-throwing the current exception object in a catch clause. Try:- The try-block contains the guarded code block that may cause the exception. The block is executed until an exception is thrown or it is completed successfully. For example, the following attempt to cast a null object raises the NullReferenceException exception: object o2 = null; try { int i2 = (int) o2; // Error } Catch:- The catch clause can be used without arguments, in which case it catches any type of exception, and referred to as the general catch clause. It can also take an object argument derived from System.Exception, in which case it handles a specific exception. For example: catch (InvalidCastException e) { } Finally:- finally is used to guarantee a statement block of code executes regardless of how the preceding try block is exited. The finally block is useful for cleaning up any resources allocated in the try block. Control is always passed to the finally block regardless of how the try block exits. The try-finally statement takes the form: try try-block finally finally-block where: try-block Contains the code segment expected to raise the exception. finally-block Contains the exception handler and the cleanup code. |