1.what is
vb.net?
Vb.net is a programming language that is available in Visual Studio. Net. It contains features of visual basic which is event based programming language and also includes object oriented concepts. [VB.Net is a programming language which is an extension of Visual Basic to make it compliant to the Dot Net Framework. Also VB.Net is fully Object Oriented unlike Visual Basic and everything in VB.Net is an object. As it is compliant to the Dot Net Framework VB.Net can make full use of Framework Class Library provided by dot Net Framework.]
2.How can we assigns items on listbox so that it will show
rowwise please write the code for it.
Lisbox1.Items.Add "Prashant"
Lisbox1.Items.Add "Chinchu"
Lisbox1.Items.Add "Pallavi"
Lisbox1.Items.Add "Suresh"
Lisbox1.Items.Add "Polika"
3.what are the properties should be given to set method?
Class Class1
' Define a local variable to store the property value.
[Ans: Only One Property.
example:
Private PropertyValue As String
' Define the property.
Public Property Prop1() As String
Get
' The Get property procedure is called when the value
' of a property is retrieved.
Return PropertyValue
End Get
Set(ByVal Value As String)
' The Set property procedure is called when the value
' of a property is modified.
' The value to be assigned is passed in the
' argument to Set.
PropertyValue = Value
End Set
End Property
End Class
4.How do you validate Date by using which validation Control?
<asp:regularexpressionvalidator id="regExpDate"
runat="server"
ValidationExpression="^\d{2}[\/-]\d{2}[\/-]\d{2,4}$"
ErrorMessage="It is not a valid date"
ControlToValidate="txtpatientvisitdate"
EnableClientScript="False"
Display="Dynamic"></asp:regularexpressionvalidator>
5.What does VS.NET contains ?
Visual Studio .Net is basically a framework which makes easy development of codes written in Various programming languages..
It contains two things
1.Framework Class Library:It contains various classes managed within various namespaces.
2.Common Language Runtime:CLR is the execution engine which helps in compiling the IL code into machine code,takes care of security issues and many other critical tasks.
Web pages,windows apps,console applications,Class libraries are various options which can be created using VS.net
6.How do you rate yourself in .NET ?
Based on Framework understanding and OOPS Concepts, Use of Different Component Library
Vb.net is a programming language that is available in Visual Studio. Net. It contains features of visual basic which is event based programming language and also includes object oriented concepts. [VB.Net is a programming language which is an extension of Visual Basic to make it compliant to the Dot Net Framework. Also VB.Net is fully Object Oriented unlike Visual Basic and everything in VB.Net is an object. As it is compliant to the Dot Net Framework VB.Net can make full use of Framework Class Library provided by dot Net Framework.]
2.How can we assigns items on listbox so that it will show
rowwise please write the code for it.
Lisbox1.Items.Add "Prashant"
Lisbox1.Items.Add "Chinchu"
Lisbox1.Items.Add "Pallavi"
Lisbox1.Items.Add "Suresh"
Lisbox1.Items.Add "Polika"
3.what are the properties should be given to set method?
Class Class1
' Define a local variable to store the property value.
[Ans: Only One Property.
example:
Private PropertyValue As String
' Define the property.
Public Property Prop1() As String
Get
' The Get property procedure is called when the value
' of a property is retrieved.
Return PropertyValue
End Get
Set(ByVal Value As String)
' The Set property procedure is called when the value
' of a property is modified.
' The value to be assigned is passed in the
' argument to Set.
PropertyValue = Value
End Set
End Property
End Class
4.How do you validate Date by using which validation Control?
<asp:regularexpressionvalidator id="regExpDate"
runat="server"
ValidationExpression="^\d{2}[\/-]\d{2}[\/-]\d{2,4}$"
ErrorMessage="It is not a valid date"
ControlToValidate="txtpatientvisitdate"
EnableClientScript="False"
Display="Dynamic"></asp:regularexpressionvalidator>
5.What does VS.NET contains ?
Visual Studio .Net is basically a framework which makes easy development of codes written in Various programming languages..
It contains two things
1.Framework Class Library:It contains various classes managed within various namespaces.
2.Common Language Runtime:CLR is the execution engine which helps in compiling the IL code into machine code,takes care of security issues and many other critical tasks.
Web pages,windows apps,console applications,Class libraries are various options which can be created using VS.net
6.How do you rate yourself in .NET ?
Based on Framework understanding and OOPS Concepts, Use of Different Component Library
7.What is intermediate language in .NET ?
.net
supports CLS i. e. Common language type. its a microsoft’s feature to bring all
languages near one roof.
When You compile .net code it doesn't converted into binary language, it converted into IL (Intermediate Language) also known as MSIL.
And from IL to binary language converted at run time, CLR manages this process. At the runtime also it not converts whole project at time to binary, only converts that part which is going to execute, this the performance of project increases. This IL can use any language which is
member of that .net studio. The assemblies (ExE, DLL) are also in IL form. So u can use any EXE or DLL created in vb.net in c#.net also.[which converts native code into byte code i.e machine understandable code.]
Disadvantages of vb ?
Following are the disadvantage of VB :
1. VB is not object oriented.
2. VB DLL does not support side-by-side execution
3. Deployment is time consuming as all the components must
be registered in the Windows registry.
[.The VB support OOP concepts, but not support fully.
2.VB does not support exception handling.
3.No multithreading mechanism.]
Advantage of vb.net over vb ?
1,supports Threading
2,powerful Exception handling
mechanism
3,having support for the
console based applications
4,More than one version of
dll is supported
[1. VB is object based while Vb.net is Object oriented
2. VB.net using OO functionality like inheritenc a,
Excepetional handling, etc
3.VB .net is strong type casting which VB lack
4.VB.net supports multi threading....]
8.Is VB.NET object oriented? What are the inheritances does VB.NET support ?
yes VB.NET ia an object oriented.
Vb.net supports all inheritance
1)single inheritance
It means Single class inheriting to single child classes
2)multiple inheritance
multiple classess inherits to single classes
3)Multilevel Inheritance
Single class inherits to one class that class inheritd to single another class
4)Heirarichal inheritance
Single class inherits to Multiple classes
5)Hybrid Inheritance
Single class inherits to different classess and that classes inherits to one class
9.Difference between VB dll and assemblies in .NET ?
Assemblies can contain DLL and EXE both. Different versions of one DLL can be handled by assemblies. They overcome the DLL Hell problem.
Assemblies Contain Manifest and Meta Data files. These are the separate files that describes the Assembly and its attributes. VB DLL is inprocess.
DLL run with an exe where as DLL are not self executable.
we can reuse DLLs .DLL are not platform independent If we have more then one Versions of a DLL we can face DLL Hell Problem.
10.How do you do multithreading application in VB ?
VB doesn't support multithreading.
[Its the fastest and an excellent application provided in VB.net. Due to which many operations can be done without any lapse of time.
The system need not wait for an application or any task to get completed, rather it runs simultaneously.]
11.what are the types of threading models in VB.net ?
There are lot of threading model available, but we focus on Threading models that are common to win32based environments singleThreaded:There is only one thread with in the process,and it is doing all the work for the process.The process must wait for the current execution of the thread to complete before it can perform another action.
Apartment Threading (Single Threaded Apartment) Apartment threaded means there are multiple threads within the application.
In single threaded apartment (STA) each thread is isolated in a separate apartment underneath the process. The process can have any number of apartments that share data through a proxy. The application defines when and for how long the thread in each apartment should execute. All requests are serialized through the Windows message queue such that only a single apartment is accessed at a time and thus only a single thread will be executing at any one time Free Threading (Multi Threaded Apartment) Free threaded applications were limited to programming languages such as C++ until the release of Microsoft .NET. The free threaded/Multi Threaded Apartment (MTA) model has a single apartment created underneath the process rather than multiple apartments. This single apartment holds multiple threads rather than just a single thread. No message queue is required because all of the threads are a part of the same apartment and can share data without a proxy. The developer must provide thread synchronization as part of the code to ensure that threads do not simultaneously access the same resources.
12.what are the advantage in vb.net and different between vb and vb.net?
vb is not follow the oops concept. But vb.net follow the oops concept.
[Adv of VB.NET vb is object based.vb.net is object oriented vb use record set for database connection vb.net use dataset for database connection]
[1. VB uses vb runtime while vb.net uses CLR
2. VB object based,vb.net is object oriented
3. VB Suports splash screen
4. VB Uses on error goto while vb.net uses Try..
Catch..Finally
5. vb.Net Supports inheritance]
13.What is the Difference between Web User Control and Web Custom Control?
web user control where it predefined attribute functionality where it resides in control library web custom control: where it is defined by
user itself and store in a custom library
[Web User Controls:
1) Easy to Create
2) Limited support for consumers who use visual design tool
3) A seperate copy of the control is required in each
application.
4)Cannot be added to toolbox in Visual Studio.
5) Good for Static Layout
Web Custom Controls:
1) Harder to Create
2) Full support for consumers
3) Only a single copy of the control is required in the GAC
4)Can be added
5) Good for Dynamic Layout]
14.What is an indexed property?
you include the index parameter in the Property statement.
In this example, the test_number parameter is the index for the Scores property.
Public Class Student
' The private array of scores.
Private m_Scores(9) As Integer
' The indexed Score property procedures.
When You compile .net code it doesn't converted into binary language, it converted into IL (Intermediate Language) also known as MSIL.
And from IL to binary language converted at run time, CLR manages this process. At the runtime also it not converts whole project at time to binary, only converts that part which is going to execute, this the performance of project increases. This IL can use any language which is
member of that .net studio. The assemblies (ExE, DLL) are also in IL form. So u can use any EXE or DLL created in vb.net in c#.net also.[which converts native code into byte code i.e machine understandable code.]
Disadvantages of vb ?
Following are the disadvantage of VB :
1. VB is not object oriented.
2. VB DLL does not support side-by-side execution
3. Deployment is time consuming as all the components must
be registered in the Windows registry.
[.The VB support OOP concepts, but not support fully.
2.VB does not support exception handling.
3.No multithreading mechanism.]
Advantage of vb.net over vb ?
1,supports Threading
2,powerful Exception handling
mechanism
3,having support for the
console based applications
4,More than one version of
dll is supported
[1. VB is object based while Vb.net is Object oriented
2. VB.net using OO functionality like inheritenc a,
Excepetional handling, etc
3.VB .net is strong type casting which VB lack
4.VB.net supports multi threading....]
8.Is VB.NET object oriented? What are the inheritances does VB.NET support ?
yes VB.NET ia an object oriented.
Vb.net supports all inheritance
1)single inheritance
It means Single class inheriting to single child classes
2)multiple inheritance
multiple classess inherits to single classes
3)Multilevel Inheritance
Single class inherits to one class that class inheritd to single another class
4)Heirarichal inheritance
Single class inherits to Multiple classes
5)Hybrid Inheritance
Single class inherits to different classess and that classes inherits to one class
9.Difference between VB dll and assemblies in .NET ?
Assemblies can contain DLL and EXE both. Different versions of one DLL can be handled by assemblies. They overcome the DLL Hell problem.
Assemblies Contain Manifest and Meta Data files. These are the separate files that describes the Assembly and its attributes. VB DLL is inprocess.
DLL run with an exe where as DLL are not self executable.
we can reuse DLLs .DLL are not platform independent If we have more then one Versions of a DLL we can face DLL Hell Problem.
10.How do you do multithreading application in VB ?
VB doesn't support multithreading.
[Its the fastest and an excellent application provided in VB.net. Due to which many operations can be done without any lapse of time.
The system need not wait for an application or any task to get completed, rather it runs simultaneously.]
11.what are the types of threading models in VB.net ?
There are lot of threading model available, but we focus on Threading models that are common to win32based environments singleThreaded:There is only one thread with in the process,and it is doing all the work for the process.The process must wait for the current execution of the thread to complete before it can perform another action.
Apartment Threading (Single Threaded Apartment) Apartment threaded means there are multiple threads within the application.
In single threaded apartment (STA) each thread is isolated in a separate apartment underneath the process. The process can have any number of apartments that share data through a proxy. The application defines when and for how long the thread in each apartment should execute. All requests are serialized through the Windows message queue such that only a single apartment is accessed at a time and thus only a single thread will be executing at any one time Free Threading (Multi Threaded Apartment) Free threaded applications were limited to programming languages such as C++ until the release of Microsoft .NET. The free threaded/Multi Threaded Apartment (MTA) model has a single apartment created underneath the process rather than multiple apartments. This single apartment holds multiple threads rather than just a single thread. No message queue is required because all of the threads are a part of the same apartment and can share data without a proxy. The developer must provide thread synchronization as part of the code to ensure that threads do not simultaneously access the same resources.
12.what are the advantage in vb.net and different between vb and vb.net?
vb is not follow the oops concept. But vb.net follow the oops concept.
[Adv of VB.NET vb is object based.vb.net is object oriented vb use record set for database connection vb.net use dataset for database connection]
[1. VB uses vb runtime while vb.net uses CLR
2. VB object based,vb.net is object oriented
3. VB Suports splash screen
4. VB Uses on error goto while vb.net uses Try..
Catch..Finally
5. vb.Net Supports inheritance]
13.What is the Difference between Web User Control and Web Custom Control?
web user control where it predefined attribute functionality where it resides in control library web custom control: where it is defined by
user itself and store in a custom library
[Web User Controls:
1) Easy to Create
2) Limited support for consumers who use visual design tool
3) A seperate copy of the control is required in each
application.
4)Cannot be added to toolbox in Visual Studio.
5) Good for Static Layout
Web Custom Controls:
1) Harder to Create
2) Full support for consumers
3) Only a single copy of the control is required in the GAC
4)Can be added
5) Good for Dynamic Layout]
14.What is an indexed property?
you include the index parameter in the Property statement.
In this example, the test_number parameter is the index for the Scores property.
Public Class Student
' The private array of scores.
Private m_Scores(9) As Integer
' The indexed Score property procedures.
Public Property Score(ByVal test_number As
Integer) As _
Integer
Get
Return m_Scores(test_number)
End Get
Set(ByVal Value As Integer)
m_Scores(test_number) = Value
End Set
End Property
End Class
Integer
Get
Return m_Scores(test_number)
End Get
Set(ByVal Value As Integer)
m_Scores(test_number) = Value
End Set
End Property
End Class
15.What is versioning in .NET?
main advantage of .net is versioning and solve very critical problem.
.net maintain one application with more then one version and also solve DLL HELL problem because it can run same application with different version at a same time [.Net have an Assembly. It gives the Portable Execution file.The main use of assembly is to maintain the Dll and exe's.
So sometimes the programmer confused to which is modified code.That time the assembly provide the Version.
That is called versioning.
It is start from 1.0.*,.......]
16.What is DLL hell?
1.Adding of a new virtual method to a class exported from a DLL can cause the following problems:
o If class already has a virtual method B and we are adding a new one named A before it, then we are changing the table of virtual methods. Now the first virtual method in the table will be A but not B and the client program which calls B will fail without recompilation as the call of B will cause the call of A and this is another method which possibly has other parameters and return type.
o When a class doesn?t have virtual methods and none of its base classes have, then adding of a new virtual method to it or to its base class will cause adding of the pointer for the table of virtual methods. This will cause change in the class size. So the error will occur after a client program will allocate memory for the class (an amount of memory that was required before the class has been changed) and will try to modify some of the class' fields explicitly or implicitly. In this case, as the pointer to the table of virtual method is added to the beginning of the class, all addresses of the class fields are shifted and thus we will get an abnormal client program behavior or a runtime error.
o In case when a class has virtual methods or any of its parent classes has, we can’t add virtual methods to classes exported from the DLL if they participate in the inheritance. We can?t add virtual methods not only to the beginning of the class declaration but also to the end of it.
1.The problem is in shifting in the table of virtual methods. Note that even if you add a new virtual method to the end of the class declaration then the child’s virtual methods will be shifted.
2.Adding of a new field (of any kind) to a class declaration can cause following problems:
1.Adding of a new field to the end of a class causes class size to change as in the case of adding of a virtual method to a class that didn?t have any. The client program will allocate less memory than it is required for a new class and this will cause referencing to the memory out of the class scope.
2.Adding of a new field between existing ones is even worse. It will case all addresses of fields after the new one to be shifted and a client application will work with the incorrect addresses while working with the fields that are situated after the new field.
We also have the problem as in the previous point here.
17.How does you call and execute a SP in .NET?
Using command object we can execute a SP. Instead of sqlquery we have to pass the SP Name.
[command.connection =connectionstring
command.commandType=commandType.storedProcedure
command.commandtext="sp_name"
command.executenonquery()]
18.Why Datareader is useful?
Data reader is useful when we just want to acccess datas from the database not when we want to perform DML operations. and It is useful when we want to perform forward only reading of datas.It wont requires any large volume of resources in the Front end.
[Datareader is read only or forward only. So it is very fast to fetch the data from database.]
19.What is the difference between Dataset and Recordset?
A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.
- A DataSet is designed to work without any continuing connection to the original data source.
- Data in a DataSet is bulk-loaded, rather than being loaded on demand.
- There's no concept of cursor types in a DataSet.
- DataSets have no current record pointer You can use For Each loops to move through the data.
- You can store many edits in a DataSet, and write them to the original data source in a single operation.
- Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.
[1)
With Data set you can retrive data from database like oracle and SQL Server and
manage them in one dataset, with recordset this is not possible.
2) All representation of Dataset is using XML while recordset uses COM.
3) Recordset can not be transmitted on HTTP while Dataset can be.]
20.How does you get record no from 5 to 15 from a dataset of 100 records?
dim dRow as data.datarow
for i as interger = 5 to 15
drow = dSet.Tables(0).Rows(i)
'process row
next i
21.What is the Difference between Dataset and Datareader?
DataReader:
Datareader is like a forward only recordset. It fetches one row at a time so very less Network Cost compare to DataSet (Fetches all the rows at a time).
DataReader is readonly so we cannot do any transaction on them. DataReader will be the best choice where we need to show the data to the user which requires no transaction ie reports. Due to DataReader is forward only we cannot fetch the data randomly. .NET Dataproviders optimizes
the datareaders to handle the huge amount of data.
DataSet:
DataSet is always a bulky object that requires lot of memory space compare to DataReader. We can say the dataset as a small database coz it stores the schema and data in the application memory area. DataSet fetches all data from the datasource at a time to its memory area.
So we can traverse through the object to get required data like qureying database.
The dataset maintains the relationships among the datatables inside it. We can manipulate the realational data as XML using dataset.We can do transactions (insert/update/delete) on them and finally the modifications can be updated to the actual database. This provides impressive
flexibility to the application but with the cost of memory space. DataSet maintains the original data and the modified data seperately which requires
more memory space. If the amount of data in the dataset is huge then it will reduce the applications performance dramatically.
The following points will improve the performance of a dataset...
1. Don't use the commandbuilder to generate the sql statements.
Though it reduces the development time the query generatedby the command builder will not be always as required.
22.How do you declare static variable and how it is declared and what is its lifetime?
Static variables are declare through the Static Var1 as Integer. The scop of the Var1 is within the module where its is Defined.
23.What is the Difference between Overriding and overloading?
overloading-------having same method name with different signatures.
overriding--------methods name and signatures must be same.
[OverLoading : All the method will share the same name but it differes based on the parameter, type of parameter and number of parameter
Overriding : The method in the derived class the has the same name in the base class and it changes the behaviour or functionality of the method in the base class.]
24.What is shadowing?
When global and local varible in the same name.
the local varibale in a mehod or function which use to override the global is called the shadowing.
ie the Global varible is being shadowed by the local varible.
25.What is an abstract class?
It is a class which contains at least one abstract method (A method without any implementation). Other methods can have implementations. This class can not be instantiated. It can always become a base class for other classes.
26.What is the DIfference between Friend and Protected Friend?
Protected variable will be accessed in inherited class, but instance variable of class cant access protected variable.
While friend variable will be accessed in inherited class as well as instance variable of class across the project.
Where we need both functionality we are using protected friend scope.
[Protected --> Accessible ONLY by 1.Derived classes 2.Within the same class
Friend --> Accessible ONLY by 1.Derived classes 2.Classes in the same assembly 3.Within the same class
Protected Friend --> Accessible ONLY by 1.Derived classes
2.Classes in the same assembly 3.Within the same class]
27.In order to get assembly info whcih namespace we should import?
system.reflection
28.ColumnMapping belongs to which namespaces?
System.Data.Common
29.Trace and Debug belongs to which namespaces?
system.process.diagnostics
30.What is the Difference between CLR & CTS?
CLR is the common language runtime. which is the feature makes the .net applications to run plantform independent langauge interoperability.
CTS Common type system is the part of the CLR which enable the Common Datatype system to All the .net languages. it also defines conventions to convert objects from one langauge to another.
31.What is CLR?
CLR means Common Language Runtime.It is Major component of the .NET frameworkIt provides number of benefits to the developers such as Exception handling,Security,Debugging and Versioning...
32.what is the root namespace for all types?
Imports system
33.What is the relation between Garbage collector and finalize and destructor?
here the GC calls an object's FINALIZE method immediately before it collects an object that is no longer referred by the application GC doesn’t actually run finalize method when the GC finds a FINALIZE method it queues the obj up for the finalizer to execute the objects method [GC checks for those resources which are no longer used by the process. To release the memory from these resources and in order to regain the memory heap GC initiates destructors to destroy such instances of the program. Before the destructor void an instance variable finalize routine gets executed. This routine performs whatever is to be done before the object return to void state or prior to release of any unused resources.]
34.What are the similarities between class and structure?
2) All representation of Dataset is using XML while recordset uses COM.
3) Recordset can not be transmitted on HTTP while Dataset can be.]
20.How does you get record no from 5 to 15 from a dataset of 100 records?
dim dRow as data.datarow
for i as interger = 5 to 15
drow = dSet.Tables(0).Rows(i)
'process row
next i
21.What is the Difference between Dataset and Datareader?
DataReader:
Datareader is like a forward only recordset. It fetches one row at a time so very less Network Cost compare to DataSet (Fetches all the rows at a time).
DataReader is readonly so we cannot do any transaction on them. DataReader will be the best choice where we need to show the data to the user which requires no transaction ie reports. Due to DataReader is forward only we cannot fetch the data randomly. .NET Dataproviders optimizes
the datareaders to handle the huge amount of data.
DataSet:
DataSet is always a bulky object that requires lot of memory space compare to DataReader. We can say the dataset as a small database coz it stores the schema and data in the application memory area. DataSet fetches all data from the datasource at a time to its memory area.
So we can traverse through the object to get required data like qureying database.
The dataset maintains the relationships among the datatables inside it. We can manipulate the realational data as XML using dataset.We can do transactions (insert/update/delete) on them and finally the modifications can be updated to the actual database. This provides impressive
flexibility to the application but with the cost of memory space. DataSet maintains the original data and the modified data seperately which requires
more memory space. If the amount of data in the dataset is huge then it will reduce the applications performance dramatically.
The following points will improve the performance of a dataset...
1. Don't use the commandbuilder to generate the sql statements.
Though it reduces the development time the query generatedby the command builder will not be always as required.
22.How do you declare static variable and how it is declared and what is its lifetime?
Static variables are declare through the Static Var1 as Integer. The scop of the Var1 is within the module where its is Defined.
23.What is the Difference between Overriding and overloading?
overloading-------having same method name with different signatures.
overriding--------methods name and signatures must be same.
[OverLoading : All the method will share the same name but it differes based on the parameter, type of parameter and number of parameter
Overriding : The method in the derived class the has the same name in the base class and it changes the behaviour or functionality of the method in the base class.]
24.What is shadowing?
When global and local varible in the same name.
the local varibale in a mehod or function which use to override the global is called the shadowing.
ie the Global varible is being shadowed by the local varible.
25.What is an abstract class?
It is a class which contains at least one abstract method (A method without any implementation). Other methods can have implementations. This class can not be instantiated. It can always become a base class for other classes.
26.What is the DIfference between Friend and Protected Friend?
Protected variable will be accessed in inherited class, but instance variable of class cant access protected variable.
While friend variable will be accessed in inherited class as well as instance variable of class across the project.
Where we need both functionality we are using protected friend scope.
[Protected --> Accessible ONLY by 1.Derived classes 2.Within the same class
Friend --> Accessible ONLY by 1.Derived classes 2.Classes in the same assembly 3.Within the same class
Protected Friend --> Accessible ONLY by 1.Derived classes
2.Classes in the same assembly 3.Within the same class]
27.In order to get assembly info whcih namespace we should import?
system.reflection
28.ColumnMapping belongs to which namespaces?
System.Data.Common
29.Trace and Debug belongs to which namespaces?
system.process.diagnostics
30.What is the Difference between CLR & CTS?
CLR is the common language runtime. which is the feature makes the .net applications to run plantform independent langauge interoperability.
CTS Common type system is the part of the CLR which enable the Common Datatype system to All the .net languages. it also defines conventions to convert objects from one langauge to another.
31.What is CLR?
CLR means Common Language Runtime.It is Major component of the .NET frameworkIt provides number of benefits to the developers such as Exception handling,Security,Debugging and Versioning...
32.what is the root namespace for all types?
Imports system
33.What is the relation between Garbage collector and finalize and destructor?
here the GC calls an object's FINALIZE method immediately before it collects an object that is no longer referred by the application GC doesn’t actually run finalize method when the GC finds a FINALIZE method it queues the obj up for the finalizer to execute the objects method [GC checks for those resources which are no longer used by the process. To release the memory from these resources and in order to regain the memory heap GC initiates destructors to destroy such instances of the program. Before the destructor void an instance variable finalize routine gets executed. This routine performs whatever is to be done before the object return to void state or prior to release of any unused resources.]
34.What are the similarities between class and structure?
- Both can have constructors, methods, properties , fields,constants , enumerations, events and event handlers.
- Structure and class can implement interface.
- Both of them can have constructor without parameter and with parameter.
- Both can have delegates and events.
[class
is a collection of methods functions and properties enumerators and fields.
structure can be defined as a tool for handling a group of logically
related data item. the main difference is class is a referance type. structure
is a reference value type.]
35.Do event have return type?
No. events do not have return type.
36. What do you mean by .Net Framework?
It is a collection of classes and services.It exists as a layer between.NET applications and underlying operating system.
i.e., it encapsulates the basic functionality that was earlier built into programming languages such as debugging and security services.
[.net framework is a collection of services & classes.it exists as a layer b/w .net applications 7 the underlying operating system.
.net framework consists of web forms,window forms & console applications that pertain to the presentation layer of the aaplication.
.net framework consists of two other components,the .net framework base classes & common language runtime(CLR).]
37. Is there any easy way to convert VB6 programs to VB.Net?
Just Open The Vb Project in Visual Studio.Net(File---> Open)
38. What is the Common Language Runtime?
CLR means commaon language runtime for the dot net frame work.
it is the frame work layer that resides above the operating system and handels/ manages the execution of the .net
applications.our .net programs don't directly communicate with the operating system but through CLR.
OUT .NET APPLICATION--->>CLR--->WINDOWS OS
39.What is VB.Net?
VB.NET has changed almost every aspect of Software development new concepts and techniques were intro the more imp thing is its a fully object oriented, new component techniques new visual tools for both local and internet interfaces.
40. How is VB.Net different from VB6?
35.Do event have return type?
No. events do not have return type.
36. What do you mean by .Net Framework?
It is a collection of classes and services.It exists as a layer between.NET applications and underlying operating system.
i.e., it encapsulates the basic functionality that was earlier built into programming languages such as debugging and security services.
[.net framework is a collection of services & classes.it exists as a layer b/w .net applications 7 the underlying operating system.
.net framework consists of web forms,window forms & console applications that pertain to the presentation layer of the aaplication.
.net framework consists of two other components,the .net framework base classes & common language runtime(CLR).]
37. Is there any easy way to convert VB6 programs to VB.Net?
Just Open The Vb Project in Visual Studio.Net(File---> Open)
38. What is the Common Language Runtime?
CLR means commaon language runtime for the dot net frame work.
it is the frame work layer that resides above the operating system and handels/ manages the execution of the .net
applications.our .net programs don't directly communicate with the operating system but through CLR.
OUT .NET APPLICATION--->>CLR--->WINDOWS OS
39.What is VB.Net?
VB.NET has changed almost every aspect of Software development new concepts and techniques were intro the more imp thing is its a fully object oriented, new component techniques new visual tools for both local and internet interfaces.
40. How is VB.Net different from VB6?
- VB6 was interpreter based language while VB.NET is a compiled language
- VB6 was not a type-safe language while VB.NET is a type safe language.
- VB6 used ?On Error Goto? syntax to handle exceptions at runtime. VB.NET uses the Try? Catch? Finally syntax to handle exceptions at runtime.
- VB.NET has much enhanced object oriented support than VB6
- VB6 does not allow developing the multithreaded applications. In VB.NET you can create multithreaded applications.
- VB6 was only considered good for desktop windows application. In VB.NET you can also develop web applications, distributed applications,
- create .NET windows and web controls and components, write windows and web services.
- In VB.NET, you can also use reflections to read the meta-data of types and using reflection emit you can also generate code to define
- and invoke types at runtime.
- VB.NET uses .NET framework class library along with specialized VB library (System.VisualBasic) as a standard library. As a result,
- the standard library for VB.NET is much enhanced and useful compared to VB6 standard library.
- VB.NET is platform independent because of .Net framework. Programs written in VB.NET can run on any platform where .Net framework is present.
- The platform include both hardware and software (operating system) platforms.
- VB6 uses COM (Component Object Model) as component architecture. VB.NET uses assemblies as its component architecture. The Assemblies
- architecture has removed a lot of problems with COM including DLL-Hell and versioning problem.
- ? Components created in VB6 (COM) need to make and update registry entries. VB.NET does not require any registry entry making the deployment
- easier.
- VB6 used ASP to build web applications. VB.NET uses ASP.NET to build web applications.
- VB6 used ADODB and record-sets to implement data access applications. VB.NET uses ADO.NET and datasets to build data access applications.
The
ADO.NET also supports the disconnected data access.
[1.VB6 was a scripting language while VB.NET is a Programming language
2.VB6 was supported Unstructured error handling by using On Error Gotos tatement.VB.NET supports structured exceptional by using Try…Catch…
Finally to handle exceptions at runtime.
3.VB.NET is completely supports object oriented features. but VB6 wont support
4.VB6 used ADO as Data access technology and record-sets to implement data access applications. Also here data transfer in the form of binary format.
VB.NET uses ADO.NET and datasets to build data access applications. The ADO.NET also supports the disconnected data access. Here the data transfer
in the form of xml format. So here their is faster data transfer.
5.Multiple versions are supported with vb.net but with vb6 its not supported
6.multithreading is supported with vb.net, but not with vb6]
41.what are Fixed memory leaks and threads locking problems?
Memory leak is a bug in the program which uses the memory continuously without releasing it until the system crash.
Thread locking problem is nothing but a deadlock situation in case of synchronous process when two consecutive threads get lock on a common resource and waiting for each other to release that. This happens usually in case when the semaphores or monitors are not used.
42. How to call a list box on the text if some one send me the code for it i understood the ?
like this what to do if we need to transfer the listbox items to the text if i am correct then my answer to this is double click on the listbox so that the eventof the listbox is displayed in the code editor
i.e private sub listbox1_selectedindexchanged......
textbox1.text=listbox1.selecteditem
43.What is the difference b/w Readonly Variable and Constant Variable?
variable used to store the data
Read only variable:-
Read only variable means read only but not allow to write
constant:
constant variable specify the constant value.
44.what is the dif b/w panel and groupbox?
Both panel and group box acts like a container to other controls they help us a lot in some applications where we want a group of controls or objects should be disabled or enabled when a specific task is performed the main difference isgroup box has a hording where u can place a
text of ure own whereas a panel is just like a frame what we used in VB but has a scrollbar(hs,vs)
45.What do you mean by 'Option Strict On' ?
Option Strict
Visual Basic language in general does not require explicit syntax to be used when performing operations that might not be optimally efficient (e.g. late binding) or that might fail at run time (e.g. narrowing conversions). This permissive semantics often prevents detection of coding errors and also affects the performance of the application.
VB.NET enables a programmer to enforce strict semantics by setting this option to "On". When used, this option should appear before any other code.
This option can be set to "On" or "Off". If this statement is not specified, by default, it is set to "Off".
Syntax: Option Strict [On / Off]
When it is set to "On", it disallows any narrowing conversions to occur without an explicit cast operator, late binding and does not let the programmer omit "As" clause in the declaration statement. Since setting it to "On" requires explicit conversion, it also requires that the
compiler be able to determine the type of each variable. Thus it is implied that Option Strict also means Option Explicit.
Visual Basic .NET allows implicit conversions of any data type to any other data type. However, data loss can occur if the value of one data type
is converted to a data type with less precision or a smaller capacity. Setting this option to "On" ensures compile-time notification of these types
of conversions so they may be avoided.
46. What are Jagged Arrays ?
a collection of discrete no of elements in each and every row is called as jagged arrays.
1)these jagged arrays doesn’t contain columns,
2)a jagged array also called as dynamic array
3)jagged array is a collection of dynamic arrays
4)these are faster and also save the memory.
syntax of jagged array:
int[][]x=new int [rows][]
here x is array name
47.What are Satellite Assemblies?
Satellite assemblies are user for localizing the applications resources. A satellite assembly is a DLL that contains only resource strings .we typically have one satellite assembly DLL for each language. Because these satellite assembly DLLs are separated from the main assembly (an .exe or DLL), it is easier to drop in 48 multi-language support as we progress in your development process.
48.How can we remove Handlers at Run time ?
RemoveHandler myobj.myEvent, AddressOf MyEventHandler
49.what is .net?
.Net is the Development Plateform which provides advanced feature facilities for the web and window application along with the window services.
The .Net is the Middle layer between the operating System and the .Net application .The feature of .Net that the .Net Component can talk with each other without worrying about the language in which they are originally.. Two main components are CLR stands for the common Language Runtime and the .Net FrameWork Base classes. The CLR performs the task of converting the IL to native code Which gives the .Net applications to be language Independent . The Other component Like .Net FramwWork Base Classes act as services to be provided to the .Net applications.
50.Can any body tell me the code procedure for preparing parameterized cristel reports?
the report should be generated by taking to or more parameters.
example: report should be genarated FROM DATE to TODATE?
We can generate Crystal Report by using date parameter, but the date format should be "yyyy,mm,dd".
Ex. CrystaReport1.SelectionFormula = "{GLNOTE.L_DT} = date(" & a & ")"
The variable 'a' should be assign with formated date
51.whats the difference bt. .dll extension and .exe extension files?
DLL : It is an inprocess server and runs in the same memory space as client application. Problem with dll is if any error comes in dll, whole application gets crashed.
Exe : It is an out of process server and rus as independent application in seperate memory. If error comes in exe, it does not affact the client application.
52.how can i extract the formated word(bold,italic,underline,font,color etc) from the msword file.?
using CommonDialog class
eg:
the code to invoke the default font dialog box by using the FontDialog control is given below:
[1.VB6 was a scripting language while VB.NET is a Programming language
2.VB6 was supported Unstructured error handling by using On Error Gotos tatement.VB.NET supports structured exceptional by using Try…Catch…
Finally to handle exceptions at runtime.
3.VB.NET is completely supports object oriented features. but VB6 wont support
4.VB6 used ADO as Data access technology and record-sets to implement data access applications. Also here data transfer in the form of binary format.
VB.NET uses ADO.NET and datasets to build data access applications. The ADO.NET also supports the disconnected data access. Here the data transfer
in the form of xml format. So here their is faster data transfer.
5.Multiple versions are supported with vb.net but with vb6 its not supported
6.multithreading is supported with vb.net, but not with vb6]
41.what are Fixed memory leaks and threads locking problems?
Memory leak is a bug in the program which uses the memory continuously without releasing it until the system crash.
Thread locking problem is nothing but a deadlock situation in case of synchronous process when two consecutive threads get lock on a common resource and waiting for each other to release that. This happens usually in case when the semaphores or monitors are not used.
42. How to call a list box on the text if some one send me the code for it i understood the ?
like this what to do if we need to transfer the listbox items to the text if i am correct then my answer to this is double click on the listbox so that the eventof the listbox is displayed in the code editor
i.e private sub listbox1_selectedindexchanged......
textbox1.text=listbox1.selecteditem
43.What is the difference b/w Readonly Variable and Constant Variable?
variable used to store the data
Read only variable:-
Read only variable means read only but not allow to write
constant:
constant variable specify the constant value.
44.what is the dif b/w panel and groupbox?
Both panel and group box acts like a container to other controls they help us a lot in some applications where we want a group of controls or objects should be disabled or enabled when a specific task is performed the main difference isgroup box has a hording where u can place a
text of ure own whereas a panel is just like a frame what we used in VB but has a scrollbar(hs,vs)
45.What do you mean by 'Option Strict On' ?
Option Strict
Visual Basic language in general does not require explicit syntax to be used when performing operations that might not be optimally efficient (e.g. late binding) or that might fail at run time (e.g. narrowing conversions). This permissive semantics often prevents detection of coding errors and also affects the performance of the application.
VB.NET enables a programmer to enforce strict semantics by setting this option to "On". When used, this option should appear before any other code.
This option can be set to "On" or "Off". If this statement is not specified, by default, it is set to "Off".
Syntax: Option Strict [On / Off]
When it is set to "On", it disallows any narrowing conversions to occur without an explicit cast operator, late binding and does not let the programmer omit "As" clause in the declaration statement. Since setting it to "On" requires explicit conversion, it also requires that the
compiler be able to determine the type of each variable. Thus it is implied that Option Strict also means Option Explicit.
Visual Basic .NET allows implicit conversions of any data type to any other data type. However, data loss can occur if the value of one data type
is converted to a data type with less precision or a smaller capacity. Setting this option to "On" ensures compile-time notification of these types
of conversions so they may be avoided.
46. What are Jagged Arrays ?
a collection of discrete no of elements in each and every row is called as jagged arrays.
1)these jagged arrays doesn’t contain columns,
2)a jagged array also called as dynamic array
3)jagged array is a collection of dynamic arrays
4)these are faster and also save the memory.
syntax of jagged array:
int[][]x=new int [rows][]
here x is array name
47.What are Satellite Assemblies?
Satellite assemblies are user for localizing the applications resources. A satellite assembly is a DLL that contains only resource strings .we typically have one satellite assembly DLL for each language. Because these satellite assembly DLLs are separated from the main assembly (an .exe or DLL), it is easier to drop in 48 multi-language support as we progress in your development process.
48.How can we remove Handlers at Run time ?
RemoveHandler myobj.myEvent, AddressOf MyEventHandler
49.what is .net?
.Net is the Development Plateform which provides advanced feature facilities for the web and window application along with the window services.
The .Net is the Middle layer between the operating System and the .Net application .The feature of .Net that the .Net Component can talk with each other without worrying about the language in which they are originally.. Two main components are CLR stands for the common Language Runtime and the .Net FrameWork Base classes. The CLR performs the task of converting the IL to native code Which gives the .Net applications to be language Independent . The Other component Like .Net FramwWork Base Classes act as services to be provided to the .Net applications.
50.Can any body tell me the code procedure for preparing parameterized cristel reports?
the report should be generated by taking to or more parameters.
example: report should be genarated FROM DATE to TODATE?
We can generate Crystal Report by using date parameter, but the date format should be "yyyy,mm,dd".
Ex. CrystaReport1.SelectionFormula = "{GLNOTE.L_DT} = date(" & a & ")"
The variable 'a' should be assign with formated date
51.whats the difference bt. .dll extension and .exe extension files?
DLL : It is an inprocess server and runs in the same memory space as client application. Problem with dll is if any error comes in dll, whole application gets crashed.
Exe : It is an out of process server and rus as independent application in seperate memory. If error comes in exe, it does not affact the client application.
52.how can i extract the formated word(bold,italic,underline,font,color etc) from the msword file.?
using CommonDialog class
eg:
the code to invoke the default font dialog box by using the FontDialog control is given below:
private sub displayfont_click(byval sender
as system.object,byval e as
system.eventargs) handles displayfont.click
fontdialog.showDialog()
textbox1.font=fontdialog1.font
end sub
the code to invoke the default font dialog box by instantiating the
textbox1.font=fontdialog1.font
end sub
the code to invoke the default font dialog box by instantiating the
fontdialog class is:
dim fdialog as new fontdialog()
private sub displayfont_click(byval sender as system.object,byval e as
dim fdialog as new fontdialog()
private sub displayfont_click(byval sender as system.object,byval e as
system.eventargs) handles displayfont.click
fdialog.showDialog()
textbox1.font=fontdialog1.font
end sub
fdialog.showDialog()
textbox1.font=fontdialog1.font
end sub
53.Differences between VB.Net and C#, related to OOPS concepts?
1. C# uses Must not Inherit, VB.Net uses sealed class
2. C# uses Internal, VB.Net uses Friend
3. VB.Net uses with events and end events
4. C# uses abstract and VB.Net uses Must Inherit
54.Can u able to get the xml document in crystal report if yes how its possible?
Yes. You have to convert XML to dataset.
55.What is different between Web.Config and Machine.Config and Where it will be ?
The ASP.NET Web.config file is used to define the configuration settings for an ASP.NET application. ASP.NET and the .NET Framework use .config files to define all configuration options. The .config files, including the ASP.NET Web.config file, are XML files.
The ASP.NET application configuration settings can be changed by creating a file called Web.config and saving it in the root folder of the application.This is how the minimal Web.config file should look like:
The first line of the
Web.config file is the same as the first line for any .config file and
specifies that this is an XML document with utf-8 character encoding type.
There
are 2 important characteristics of the Web.config file. The first one is that
if you change your Web.config file, you don?t need to re-compile your ASP.NET
application.
The second one is that the Web.config file cannot be viewed in directly in a browser.
Server-wide configuration settings for the .NET Framework are defined in a file called Machine.config. The settings in the Machine.config file can be changed and those settings affect all .NET applications on the server.what if the Machine.config file defines different settings than the ones defined in your Web.config file? The settings in the Web.config file override the settings in the Machine.config file.
[A web.config file is used to configure one asp .net web application. Each Asp.net application has a web.config file. A Machine.config file is used to configure the applications in a particular machine. Configuration done in machine.config file is affected on any application that runs on a particular machine. ]
56.How to store and retrieve images in sql server database through VB.NET?
To store image in database 1st u need to make table like this
The second one is that the Web.config file cannot be viewed in directly in a browser.
Server-wide configuration settings for the .NET Framework are defined in a file called Machine.config. The settings in the Machine.config file can be changed and those settings affect all .NET applications on the server.what if the Machine.config file defines different settings than the ones defined in your Web.config file? The settings in the Web.config file override the settings in the Machine.config file.
[A web.config file is used to configure one asp .net web application. Each Asp.net application has a web.config file. A Machine.config file is used to configure the applications in a particular machine. Configuration done in machine.config file is affected on any application that runs on a particular machine. ]
56.How to store and retrieve images in sql server database through VB.NET?
To store image in database 1st u need to make table like this
CREATE TABLE PicImage
(
Picid int,
Pic Image
)
Now in vb.net coding u have to write code like this
Dim ms As New MemoryStream
pic_photo.Image.Save(ms, pic_photo.Image.RawFormat)
arrImage = ms.GetBuffer
ms.Flush()
(
Picid int,
Pic Image
)
Now in vb.net coding u have to write code like this
Dim ms As New MemoryStream
pic_photo.Image.Save(ms, pic_photo.Image.RawFormat)
arrImage = ms.GetBuffer
ms.Flush()
Now
pass arrImage in ur insert query.
57.What is the difference between vb and vb.net ?
How to insert row by row data in datagrid ?
How to work with repeater controls and give small example program ?
1. Visual Basic.NET is object oriented but VB 6 is not so.
2. Visual Basic.NET supports multi threading but VB doesnt support.
3. Visual basic.NET supports Managed Code extensions but VB doesnt support.
4. Both Vb and VB.NET support command line programs.
5. Both VB and VB.NET support COM and COM+ applications.
6. VB.NET is strongly typed but VB is not so.
57.What is the difference between vb and vb.net ?
How to insert row by row data in datagrid ?
How to work with repeater controls and give small example program ?
1. Visual Basic.NET is object oriented but VB 6 is not so.
2. Visual Basic.NET supports multi threading but VB doesnt support.
3. Visual basic.NET supports Managed Code extensions but VB doesnt support.
4. Both Vb and VB.NET support command line programs.
5. Both VB and VB.NET support COM and COM+ applications.
6. VB.NET is strongly typed but VB is not so.
Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim dr As SqlDataReader
Dim table As New DataTable
constructor initialze the cn object like eg
cn = new sqlconnection("server=name;database=name;uid=name;pwd=name;")
write it in the button .click event that add the table dynamicaaly created to
Dim cmd As SqlCommand
Dim dr As SqlDataReader
Dim table As New DataTable
constructor initialze the cn object like eg
cn = new sqlconnection("server=name;database=name;uid=name;pwd=name;")
write it in the button .click event that add the table dynamicaaly created to
datagrid
Try
cmd = New SqlCommand
cmd.CommandType = CommandType.Text
cmd.Connection = cn
cmd.CommandText = "select * from manas"
cn.Open()
dr = cmd.ExecuteReader()
Dim i As Integer
For i = 0 To dr.FieldCount - 1
table.Columns.Add(i)
Next
Dim row As DataRow
While dr.Read()
row = table.NewRow()
For i = 0 To dr.FieldCount - 1
row(i) = dr(i)
Next
table.Rows.Add(row)
End While
DataGrid1.DataSource = table
Catch ex As Exception
MsgBox(ex.Message & ex.StackTrace)
Finally
cn.Close()
dr.Close()
End Try
Try
cmd = New SqlCommand
cmd.CommandType = CommandType.Text
cmd.Connection = cn
cmd.CommandText = "select * from manas"
cn.Open()
dr = cmd.ExecuteReader()
Dim i As Integer
For i = 0 To dr.FieldCount - 1
table.Columns.Add(i)
Next
Dim row As DataRow
While dr.Read()
row = table.NewRow()
For i = 0 To dr.FieldCount - 1
row(i) = dr(i)
Next
table.Rows.Add(row)
End While
DataGrid1.DataSource = table
Catch ex As Exception
MsgBox(ex.Message & ex.StackTrace)
Finally
cn.Close()
dr.Close()
End Try
58.how to check for a particular record whether it is present or not in dataset ?
if the record is not present i want to display a message as no records what is the code for checking
if you are using "DataReader"
then
if DataReaderName.HasRows then
statements
else
statements
end if
if you are using "DataSet" then
if DataSetName.TABLES.("tablename").ROWS.COUNT=0 THEN
statements.
end if
if DataReaderName.HasRows then
statements
else
statements
end if
if you are using "DataSet" then
if DataSetName.TABLES.("tablename").ROWS.COUNT=0 THEN
statements.
end if
59. I was asked in interview that if i have created a class and i don't want the class to be inherited by any other members without me which key or function i have to use?
VB: for class NotInheritable [MyClass]
For method: NotOverridable [MyMethod]
C# For class or method :sealed[MyClassMyMethod]{}
60.what is STA in .NET?
single-threaded apartments (the apartment model process) offers a message-based paradigm for dealing with multiple objects running concurrently.
It enables you to write more efficient code by allowing a thread, while it waits for some time-consuming operation to complete, to allow another thread to be executed.Each thread in a process that is initialized as an apartment model process, and that retrieves and dispatches window messages, is a single-threaded apartment thread. Each thread lives within its own apartment. Within an apartment, interface pointers can be passed without marshaling, and therefore, all objects in one single-threaded apartment thread communicate directly. A logical grouping of related objects that all execute on the same thread, and therefore must have synchronous execution, could live on the same single-threaded apartment thread.
However, an apartment model object cannot reside on more than one thread. Calls to objects in other processes must be made within the context of the owning process, so distributed COM switches threads for you automatically when you call on a proxy.
61.How would you implement inheritance using VB.NET ?
Using VB.NET we can create a class that provides basic functionality so that other classes can inherit its members.
VB.NET provides the 'Inherits' keyword to implement inheritance. By using the keyword 'Inherits' we can inherit the characteristics of a class into another class.
62.What is assembly in .NET and What do you mean by protected class always present in the same assembly?
Assemblies are building blocks of framework. There are mainly two types of assemblies
a) Private Assembly
b) Shared Assembly
63 what is the diff between VB MDI form and .net MDI form?
In VB MDI form is created by adding MDI Form to the project and adding child forms by setting MDICHILD property of the child form.
In .NET there is no MDI form, any form can be made a MDI parent by setting IsMdiContainer property to TRUE Furthermore, there are changes in the properties, methods and basic behavior of the MDI Forms, like ability to set Background Color is not available in .NET, ability to add controls to MDI form (although they don't behave properly), ActiveForm to ActiveMdiChild, Arrange method to LayoutMdi, etc.
64 what is the advantage of option strict on?
Visual Basic allows conversions of many data types to other data types. Data loss can occur when the value of one data type is converted to a data type with less precision or smaller capacity. A run-time error occurs if such a narrowing conversion fails. Option Strict ensures compile-time notification of these narrowing conversions so they can be avoided.
In addition to disallowing implicit narrowing conversions, Option Strict generates an error for late binding. An object is late bound when it is assigned to a variable that is declared to be of type Object. Because Option Strict On provides strong typing, prevents unintended type conversions with data loss, disallows late binding, and improves performance, its use is strongly recommended.
65.What is MISL CODE?
MSIL code is the Microsoft Intermediate Language. This is the code created by the CLR from the source code. This MSIL code is converted to machine/native code by JIT compiler. This machine code is actually the code which runs.
66.What is the difference between a "jagged array" and multidimensional array" ?
Can anyone show me it practically ?
multidimentional array has same size in all dimentions but jagged is the type of multidimentional array which has different size for its dimensions.
int array[3][3][3]; //multidimentional array
int array[3][1][6]; //jagged array
What is Late Binding and Early Binding ?,
Late Binding: runtime binding
Early Binding: compile time binding as compilation is done before executing an application so it is called early binding.
67.What is the exact defination of "Object"?
A real world entity which has some specific attributes related to its characteristics and operations or methods associated with its attributes.
68.how do you use two datareaders at the same time in a vb.net windows application ?
for example:
while(datareader1.read())
while(datareader2.read())
end while
end while
this is not allowed even though both datareaders have two different sets of data
69.What are the difference between dispose(), close(), exit(), end()? When do we use them?
dispose(): should release all the resources that it owns.
close():closing the application
exit():Exiting from the loop
end():stops the execution of the page/function/procedure
70.When do we use imports.system.sqlclient and when imports.system.oledb?
System.Data.OleDB
It contains the objects that we use to connect to a data source via an OleDB provider , such as OleDbConnection, OleDBCOmmand System.Data.SqlClient
It contains objects that we use to connect to a data source via Tabular data stream interface provided by Microsoft Sql Server.
This can be generally used to provide better performance because it removes some of the intermediate layers required by the OleDB provider.
71. What is the advantage of packaging over xcopy in .NET?
With the help of xcopy we solve the problem of DLL HELL and com dependencies
when we make xcopy of project all the dll, dependencies, assembly are updated automaticaly it's a powerful feature of a .NET
72.What is the difference between DataTable and DataSet?
Data table is a collection of record's that consist the single table
Whenever dataset is collection of data table and it is provide interface between database and datatable 1 dataset consist multiple table.
73.What is the size of .NET object?
Default size when a class gets loaded in memory is 8 bytes
74.What is the significance of delegates. Where should they be used? what are the situations where we require them?
Delegates are used as pointer to hold the controls actually i used the delegates when there is problem in VB.Net 2005 where each control is already threaded, to use my personla thread on these control i used delegates
Private Delegate Sub dd()
Dim d1 As New dd(AddressOf c1)
Dim t1 As New Threading.Thread(AddressOf thread1)
public sub Thread1()
r1 =
Me.Label1.BeginInvoke(d1)
Me.Label1.EndInvoke(r1)
end sub
Public Sub c1()
Me.Label1.Text = ct1
Me.Label1.Refresh()
End Sub
Dim d1 As New dd(AddressOf c1)
Dim t1 As New Threading.Thread(AddressOf thread1)
public sub Thread1()
r1 =
Me.Label1.BeginInvoke(d1)
Me.Label1.EndInvoke(r1)
end sub
Public Sub c1()
Me.Label1.Text = ct1
Me.Label1.Refresh()
End Sub
75.What is the difference between manifest and metadata?
Manifest and metadata are 2 parts of assembly architecture.
Manifest is used for storing AssemblyName, AssemblyTitle, publicKey.
Metadata contains Namespaces, Classes.
76.What is the use of “MustInherit” keyword in VB.NET ?
If you want to create a abstract class in VB.NET it’s done by using “MustInherit" keyword.You can not create an object of a class which is marked as “MustInherit”. When you define “MustInherit” keyword for class you can only use the class by inheriting.
1.What is C#.Net?
C# (pronounced C Sharp) is a multi-paradigm programming language that encompases functional, imparitive, generic, Object-Oriented (class-based), and component-oriented programing disciplines. It was developed by Microsoft. C# is 44 programing languages supported by the .NET Frameworks.
2.What is the difference between realloc() and free()?
The free subroutine frees a block of memory previously allocated by the malloc subroutine. Undefined results occur if the Pointer parameter is not a valid pointer. If the Pointer parameter is a null value, no action will occur. The realloc subroutine changes the size of the block of memory pointed to by the Pointer parameter to the number of bytes specified by the Size parameter and returns a new pointer to the block.
The pointer specified by the Pointer parameter must have been created with the malloc, calloc, or realloc subroutines and not been deallocated with the free or realloc subroutines. Undefined results occur if the Pointer parameter is not a valid pointer.
3.What is function overloading and operator overloading?
Function overloading: C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types.
Operator overloading allows existing C++ operators to be redefined so that they work on objects of user-defined classes.
Overloaded operators are syntactic sugar for equivalent function calls. They form a pleasant facade that doesn't add anything fundamental to the language (but they can improve understandability and reduce maintenance costs).
4.What is the difference between declaration and definition?
The declaration tells the compiler that at some later point we plan to present the definition of this declaration.
E.g :
void stars ()
//function declaration
The definition contains the actual implementation.
E.g.:
void stars () // declarator
{
for(int j=10; j > =0; j--) //function body
cout << *;
cout << endl; }
{
for(int j=10; j > =0; j--) //function body
cout << *;
cout << endl; }
5.What are the advantages of inheritance?
It permits code reusability. Reusability saves time in program development. It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional.
6.How do you write a function that can reverse a linked-list?
void reverselist(void)
{
if(head==0)
return;
if(head->next==0)
return;
if(head->next==tail)
{
head->next = 0;
tail->next = head;
}
else
{
node* pre = head;
node* cur = head->next;
node* curnext = cur->next;
head->next = 0;
cur-> next = head;
for(; curnext!=0; )
{
cur->next = pre;
pre = cur;
cur = curnext;
curnext = curnext->next;
}
curnext->next = cur;
}
}
{
if(head==0)
return;
if(head->next==0)
return;
if(head->next==tail)
{
head->next = 0;
tail->next = head;
}
else
{
node* pre = head;
node* cur = head->next;
node* curnext = cur->next;
head->next = 0;
cur-> next = head;
for(; curnext!=0; )
{
cur->next = pre;
pre = cur;
cur = curnext;
curnext = curnext->next;
}
curnext->next = cur;
}
}
7.What do you mean by inline function?
The idea behind inline functions is to insert the code of a called function at the point where the function is called. If done carefully, this can improve the application's performance in exchange for increased compile time and possibly (but not always) an increase in the size of the generated binary executables.
Write a program that ask for user input from 5 to 9 then calculate the average
#include "iostream.h"
int main() {
int MAX = 4;
int total = 0;
int average;
int numb;
for (int i=0; i<MAX; i++) {
cout << "Please enter your input between 5 and 9: ";
cin >> numb;
while ( numb<5 || numb>9) {
cout << "Invalid input, please re-enter: ";
cin >> numb;
}
total = total + numb;
}
average = total/MAX;
cout << "The average number is: " << average << "\n";
return 0;
}
Write a short code using C++ to printout all odd number from 1 to 100 using a for
int main() {
int MAX = 4;
int total = 0;
int average;
int numb;
for (int i=0; i<MAX; i++) {
cout << "Please enter your input between 5 and 9: ";
cin >> numb;
while ( numb<5 || numb>9) {
cout << "Invalid input, please re-enter: ";
cin >> numb;
}
total = total + numb;
}
average = total/MAX;
cout << "The average number is: " << average << "\n";
return 0;
}
Write a short code using C++ to printout all odd number from 1 to 100 using a for
loop
for( unsigned int i = 1; i < = 100; i++ )
if( i & 0x00000001 )
cout << i << \",\";
for( unsigned int i = 1; i < = 100; i++ )
if( i & 0x00000001 )
cout << i << \",\";
8.What is public, protected, private?
Public, protected and private are three access specifier in C++.
Public data members and member functions are accessible outside the class.
Protected data members and member functions are only available to derived classes.
Private data members and member functions can’t be accessed outside the class. However there is an exception can be using friend classes.
Write a function that swaps the values of two integers, using int* as the argument type.
void swap(int* a, int*b)
{
int t;
t = *a;
*a = *b;
*b = t;
}
int t;
t = *a;
*a = *b;
*b = t;
}
9.Tell how to check whether a linked list is circular?
Create two pointers, each set to the start of the list. Update each as follows:
while (pointer1)
{
pointer1 = pointer1->next;
pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;
if (pointer1 == pointer2) {
print (\"circular\n\");
}
}
pointer1 = pointer1->next;
pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;
if (pointer1 == pointer2) {
print (\"circular\n\");
}
}
10. OK, why does this work?
If a list is circular, at some point pointer2 will wrap around and be either at the item just before pointer1, or the item before that. Either way,
it’s either 1 or 2 jumps until they meet.
11.What are the advantages of inheritance?
• It permits code reusability.
• Reusability saves time in program development.
• It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional.
12.What is the difference between declaration and definition?
The declaration tells the compiler that at some later point we plan to present the definition of this declaration.
E.g: void stars () //function declaration
The definition contains the actual implementation.
E.g:
void stars () // declarator
{
for(int j=10; j>=0; j--) //function body
cout<<”*”;
cout<<endl;
{
for(int j=10; j>=0; j--) //function body
cout<<”*”;
cout<<endl;
}
13.What is the difference between an ARRAY and a LIST?
Array is collection of homogeneous elements.
List is collection of heterogeneous elements.
For Array memory allocated is static and continuous.
For List memory allocated is dynamic and Random.
Array: User need not have to keep in track of next memory allocation.
List: User has to keep in Track of next location where memory is allocated.
14.What is a template?
Templates allow to create generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types. Until certain point they fulfill the functionality of a macro. Its prototype is any of the two following ones:
template <class indetifier> function_declaration; template <typename indetifier> function_declaration;
The only difference between both prototypes is the use of keyword class or typename, its use is indistinct since both expressions have exactly the same meaning and behave exactly the same way.
15.Define a constructor - What it is and how it might be called?
constructor is a member function of the class, with the name of the function being the same as the class name. It also specifies how the object
should be initialized.
Ways of calling constructor:
1) Implicitly: automatically by complier when an object is created.
2) Calling the constructors explicitly is possible, but it makes the code unverifiable.
16.Explain differences between eg. new() and malloc()?
new() allocates continous space for the object instace
malloc() allocates distributed space.
new() is castless, meaning that allocates memory for this specific type,
malloc(), calloc() allocate space for void * that is cated to the specific class type pointer.
17.What is the difference between class and structure?
Structure: Initially (in C) a structure was used to bundle different type of data types together to perform a particular functionality.
But C++ extended the structure to contain functions also. The major difference is that all declarations inside a structure are by default public.
Class: Class is a successor of Structure. By default all the members inside the class are private.
18.What is RTTI?
Runtime type identification (RTTI) lets you find the dynamic type of an object when you have only a pointer or a reference to the base type.
RTTI is the official way in standard C++ to discover the type of an object and to convert the type of a pointer or reference (that is, dynamic typing).
The need came from practical experience with C++. RTTI replaces many Interview Questions - Homegrown versions with a solid, consistent approach.
19.What is encapsulation?
Packaging an object’s variables within its methods is called encapsulation.
20.What is an object?
Object is a software bundle of variables and related methods. Objects have state and behavior.
21.How can you tell what shell you are running on UNIX system?
You can do the Echo $RANDOM. It will return a undefined variable if you are from the C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit random numbers if you are from the Korn shell. You could also do a ps -l and look for the shell with the highest PID.
22.What do you mean by inheritance?
Inheritance is the process of creating new classes, called derived classes, from existing classes or base classes. The derived class inherits all the capabilities of the base class, but can add embellishments and refinements of its own.
Describe PRIVATE, PROTECTED and PUBLIC – the differences and give examples.
class Point2D
{
int x; int y;
public int color;
protected bool pinned;
public Point2D() : x(0), y(0) {}//default (no argument) constructor
};
{
int x; int y;
public int color;
protected bool pinned;
public Point2D() : x(0), y(0) {}//default (no argument) constructor
};
Point2D
MyPoint;
You cannot directly access private data members when they are declared (implicitly) private:
MyPoint.x = 5; // Compiler will issue a compile ERROR
//Nor yoy can see them:
int x_dim = MyPoint.x; // Compiler will issue a compile ERROR
On the other hand, you can assign and read the public data members:
MyPoint.color = 255; // no problem
int col = MyPoint.color; // no problem
With protected data members you can read them but not write them: MyPoint.pinned = true; // Compiler will issue a compile ERROR
bool isPinned = MyPoint.pinned; // no problem
What is namespace?
Namespaces allow us to group a set of global classes, objects and/or functions under a name. To say it somehow, they serve to split the global scope in sub-scopes known as namespaces.
The form to use namespaces is:
namespace identifier { namespace-body }
Where identifier is any valid identifier and namespace-body is the set of classes, objects and functions that are included within the namespace.
For example:
namespace general { int a, b; } In this case, a and b are normal variables integrated within the general namespace. In order to access to these variables from outside the namespace we have to use the scope operator ::. For example, to access the previous variables we would have to put:
general::a general::b
The functionality of namespaces is specially useful in case that there is a possibility that a global object or function can have the same name
than another one, causing a redefinition error.
23.What is a COPY CONSTRUCTOR and when is it called?
A copy constructor is a method that accepts an object of the same class and copies it’s data members to the object on the left part of assignement:
You cannot directly access private data members when they are declared (implicitly) private:
MyPoint.x = 5; // Compiler will issue a compile ERROR
//Nor yoy can see them:
int x_dim = MyPoint.x; // Compiler will issue a compile ERROR
On the other hand, you can assign and read the public data members:
MyPoint.color = 255; // no problem
int col = MyPoint.color; // no problem
With protected data members you can read them but not write them: MyPoint.pinned = true; // Compiler will issue a compile ERROR
bool isPinned = MyPoint.pinned; // no problem
What is namespace?
Namespaces allow us to group a set of global classes, objects and/or functions under a name. To say it somehow, they serve to split the global scope in sub-scopes known as namespaces.
The form to use namespaces is:
namespace identifier { namespace-body }
Where identifier is any valid identifier and namespace-body is the set of classes, objects and functions that are included within the namespace.
For example:
namespace general { int a, b; } In this case, a and b are normal variables integrated within the general namespace. In order to access to these variables from outside the namespace we have to use the scope operator ::. For example, to access the previous variables we would have to put:
general::a general::b
The functionality of namespaces is specially useful in case that there is a possibility that a global object or function can have the same name
than another one, causing a redefinition error.
23.What is a COPY CONSTRUCTOR and when is it called?
A copy constructor is a method that accepts an object of the same class and copies it’s data members to the object on the left part of assignement:
class Point2D
{
int x; int y;
public int color;
protected bool pinned;
public Point2D() : x(0), y(0) {}//default (no argument) constructor
public Point2D( const Point2D & ) ;
};
Point2D::Point2D( const Point2D & p )
{
this->x = p.x;
this->y = p.y;
this->color = p.color;
this->pinned = p.pinned;
}
main()
int x; int y;
public int color;
protected bool pinned;
public Point2D() : x(0), y(0) {}//default (no argument) constructor
public Point2D( const Point2D & ) ;
};
Point2D::Point2D( const Point2D & p )
{
this->x = p.x;
this->y = p.y;
this->color = p.color;
this->pinned = p.pinned;
}
main()
{
Point2D MyPoint;
MyPoint.color = 345;
Point2D AnotherPoint = Point2D( MyPoint );
Point2D MyPoint;
MyPoint.color = 345;
Point2D AnotherPoint = Point2D( MyPoint );
// now AnotherPoint has color = 345
}
24.What is Boyce Codd Normal form?
A relation schema R is in BCNF with respect to a set F of functional dependencies if for all functional dependencies in F+ of the form a-> ,
where a and b is a subset of R, at least one of the following holds:
* a- > b is a trivial functional dependency (b is a subset of a)
* a is a superkey for schema R
25.What is virtual class and friend class?
Friend classes are used when two or more classes are designed to work together and need access to each other's implementation in ways that the rest of the world shouldn't be allowed to have. In other words, they help keep private things private. For instance, it may be desirable for class DatabaseCursor to have more privilege to the internals of class Database than main() has.
26.What are 2 ways of exporting a function from a DLL?
1.Taking a reference to the function from the DLL instance.
2. Using the DLL ’s Type Library
27.What is the difference between an object and a class?
Classes and objects are separate but related concepts. Every object belongs to a class and every class contains one or more related objects.
- A Class is static. All of the attributes of a class are fixed before, during, and after the execution of a program. The attributes of a class don't change.
- The class to which an object belongs is also (usually) static. If a particular object belongs to a certain class at the time that it is created then it almost certainly will still belong to that class right up until the time that it is destroyed.
- An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed. Also during that lifetime, the attributes of the object may undergo significant change.
28.What is a class?
Class is a user-defined data type in C++. It can be created to solve a particular kind of problem. After creation the user need not know the specifics of the working of a class.
29.What is friend function?
As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be listed in the class definition.
30.What is abstraction?
Abstraction is of the process of hiding unwanted details from the user.
31.What are virtual functions?
A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class.
31.What is the difference between an external iterator and an internal iterator? Describe an advantage of an external iterator?
An internal iterator is implemented with member functions of the class that has items to step through. .An external iterator is implemented as a separate class that can be "attach" to the object that has items to step through. .An external iterator has the advantage that many difference iterators can be active simultaneously on the same object.
32.What is a scope resolution operator?
A scope resolution operator (::), can be used to define the member functions of a class outside the class.
33.What do you mean by pure virtual functions?
A pure virtual member function is a member function that the base class forces derived classes to provide. Normally these member functions have no implementation. Pure virtual functions are equated to zero.
class Shape { public: virtual void draw() = 0; };
34.What is polymorphism? Explain with an example?
"Poly" means "many" and "morph" means "form". Polymorphism is the ability of an object (or reference) to assume (be replaced by) or become many different forms of object.
Example: function overloading, function overriding, virtual functions. Another example can be a plus ‘+’ sign, used for adding two integers or for
using it to concatenate two strings.
35.What is the difference between char a[] = “string”; and char *p = “string”;?
In the first case 6 bytes are allocated to the variable a which is fixed, where as in the second case if *p is assigned to some other value the allocate memory can change.
36.How do I initialize a pointer to a function?
This is the way to initialize a pointer to a function
24.What is Boyce Codd Normal form?
A relation schema R is in BCNF with respect to a set F of functional dependencies if for all functional dependencies in F+ of the form a-> ,
where a and b is a subset of R, at least one of the following holds:
* a- > b is a trivial functional dependency (b is a subset of a)
* a is a superkey for schema R
25.What is virtual class and friend class?
Friend classes are used when two or more classes are designed to work together and need access to each other's implementation in ways that the rest of the world shouldn't be allowed to have. In other words, they help keep private things private. For instance, it may be desirable for class DatabaseCursor to have more privilege to the internals of class Database than main() has.
26.What are 2 ways of exporting a function from a DLL?
1.Taking a reference to the function from the DLL instance.
2. Using the DLL ’s Type Library
27.What is the difference between an object and a class?
Classes and objects are separate but related concepts. Every object belongs to a class and every class contains one or more related objects.
- A Class is static. All of the attributes of a class are fixed before, during, and after the execution of a program. The attributes of a class don't change.
- The class to which an object belongs is also (usually) static. If a particular object belongs to a certain class at the time that it is created then it almost certainly will still belong to that class right up until the time that it is destroyed.
- An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed. Also during that lifetime, the attributes of the object may undergo significant change.
28.What is a class?
Class is a user-defined data type in C++. It can be created to solve a particular kind of problem. After creation the user need not know the specifics of the working of a class.
29.What is friend function?
As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be listed in the class definition.
30.What is abstraction?
Abstraction is of the process of hiding unwanted details from the user.
31.What are virtual functions?
A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class.
31.What is the difference between an external iterator and an internal iterator? Describe an advantage of an external iterator?
An internal iterator is implemented with member functions of the class that has items to step through. .An external iterator is implemented as a separate class that can be "attach" to the object that has items to step through. .An external iterator has the advantage that many difference iterators can be active simultaneously on the same object.
32.What is a scope resolution operator?
A scope resolution operator (::), can be used to define the member functions of a class outside the class.
33.What do you mean by pure virtual functions?
A pure virtual member function is a member function that the base class forces derived classes to provide. Normally these member functions have no implementation. Pure virtual functions are equated to zero.
class Shape { public: virtual void draw() = 0; };
34.What is polymorphism? Explain with an example?
"Poly" means "many" and "morph" means "form". Polymorphism is the ability of an object (or reference) to assume (be replaced by) or become many different forms of object.
Example: function overloading, function overriding, virtual functions. Another example can be a plus ‘+’ sign, used for adding two integers or for
using it to concatenate two strings.
35.What is the difference between char a[] = “string”; and char *p = “string”;?
In the first case 6 bytes are allocated to the variable a which is fixed, where as in the second case if *p is assigned to some other value the allocate memory can change.
36.How do I initialize a pointer to a function?
This is the way to initialize a pointer to a function
void fun(int a)
{
}
void main()
{
void (*fp)(int);
fp=fun;
fp(1);
}
{
}
void main()
{
void (*fp)(int);
fp=fun;
fp(1);
}
37.How do you link a C++ program to C functions?
By using the extern "C" linkage specification around the C function declarations.
38.Explain the scope resolution operator?
It permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope.
39.What are the differences between a C++ struct and C++ class?
The default member and base-class access specifier are different.
40.How does throwing and catching exceptions differ from using setjmp and longjmp?
The throw operation calls the destructors for automatic objects instantiated since entry to the try block.
41.What is a default constructor?
Default constructor WITH arguments
class B
{
public: B
(int m = 0) : n (m)
{
{
public: B
(int m = 0) : n (m)
{
}
int n;
};
int main(int argc, char *argv[])
{
B b;
return 0;
}
int n;
};
int main(int argc, char *argv[])
{
B b;
return 0;
}
42.What is a conversion constructor?
A constructor that accepts one argument of a different type.
43.What is the difference between a copy constructor and an overloaded assignment operator?
A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.
44.When should you use multiple inheritance?
There are three acceptable answers: "Never," "Rarely," and "When the problem domain cannot be accurately modeled any other way."
45.When is a template a better solution than a base class?
When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus, the generosity) to the designer of the container or manager class.
46.What is a mutable member?
One that can be modified by the class even when the object of the class or the member function doing the modification is const.
47.What is an explicit constructor?
A conversion constructor declared with the explicit keyword. The compiler does not use an explicit constructor to implement an implied conversion of types. It’s purpose is reserved explicitly for construction.
48.What is the Standard Template Library (STL)?
A library of container templates approved by the ANSI committee for inclusion in the standard C++ specification.
A programmer who then launches into a discussion of the generic programming model, iterators, allocators, algorithms, and such, has a higher than average understanding of the new technology that STL brings to C++ programming.
49.What is the difference between Mutex and Binary semaphore?
semaphore is used to synchronize processes. where as mutex is used to provide synchronization between threads running in the same process.
50.In C++, what is the difference between method overloading and method overriding?
Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overriding is the ability of the inherited class rewriting the virtual method of the base class.
51.What methods can be overridden in Java?
In C++ terminology, all public methods in Java are virtual. Therefore, all Java methods can be overwritten in subclasses except those that are declared final, static, and private.
52.What are the defining traits of an object-oriented language?
The defining traits of an object-oriented langauge are:
* encapsulation
* inheritance
* polymorphism
53.Assignment Operator - What is the diffrence between a "assignment operator" and a "copy constructor"?
In assignment operator, you are assigning a value to an existing object. But in copy constructor, you are creating a new object and then assigning a value to that object. For example:
complex c1,c2;
c1=c2; //this is assignment
complex c3=c2; //copy constructor
54.STL Containers - What are the types of STL containers?
There are 3 types of STL containers:
1. Adaptive containers like queue, stack
2. Associative containers like set, map
3. Sequence containers like vector, deque
55.What is the need for a Virtual Destructor ?
Destructors are declared as virtual because if do not declare it as virtual the base class destructor will be called before the derived class destructor and that will lead to memory leak because derived class, objects will not get freed. Destructors are declared virtual so as to bind objects to the methods at runtime so that appropriate destructor is called.
56.What is Object Oriented Programming ?
It is a problem solving technique to develop software systems. It is a technique to think real world in terms of objects. Object maps the software model to real world concept. These objects have responsibilities and provide services to application or other objects.
57. What’s a Class ?
A class describes all the attributes of objects, as well as the methods that implement the behavior of member objects. It’s a comprehensive data type which represents a blue printof objects. It’s a template of object.
58. What’s an Object ?
It is a basic unit of a system. An object is an entity that has attributes, behavior, and identity. Objects are members of a class. Attributes and behavior of an object are defined by the class definition.
59. What is the relation between Classes and Objects ?
They look very much same but are not same. Class is a definition, while object is a instance of the class created. Class is a blue print while objects are actual objects existing in real world. Example we have class CAR which has attributes and methods like Speed,Brakes, Type of Car etc. Class CAR is just a prototype, now we can create real time objects which can be used to provide functionality. Example we can create a Maruti car object with 100 km speed and urgent brakes.
60.What is a Interface ?
Interface is a contract that defines the signature of the functionality. So if a class is implementing a interface it says to the outer world, that it provides specific behavior.
Example if a class is implementing Idisposable interface that means it has a functionality to release unmanaged resources. Now external objects using this class know that it has contract by which it can dispose unused unmanaged objects.
- Single Class can implement multiple interfaces.
- If a class implements a interface then it has to provide implementation to all its methods.
Note:- In CD sample
“WindowsInterFace” is provided, which has a simple interface implemented.
In sample there are two files.One has the interface definition and other class implements
the interface. Below is the source code “IInterface” is the interface and “ClsDosomething”
implements the “IInterface”. This sample just displays a simple message box.
In sample there are two files.One has the interface definition and other class implements
the interface. Below is the source code “IInterface” is the interface and “ClsDosomething”
implements the “IInterface”. This sample just displays a simple message box.
Public Interface IInterFace
Sub DoSomething()
End Interface
Public Class ClsDoSomething
Implements IInterFace
Public Sub DoSomething() Implements
WindowsInterFace.IInterFace.DoSomething
MsgBox(“Interface implemented”)
End Sub
End Class
Sub DoSomething()
End Interface
Public Class ClsDoSomething
Implements IInterFace
Public Sub DoSomething() Implements
WindowsInterFace.IInterFace.DoSomething
MsgBox(“Interface implemented”)
End Sub
End Class
Fig: Interface in action
61.What is difference between abstract classes and interfaces?
Following are the differences between abstract and interfaces :-
- Abstract classes can have concrete methods while interfaces have no methods implemented.
- Interfaces do not come in inheriting chain, while abstract classes come in inheritance.
62.What is a delegate ?
Delegate is a class that can hold a reference to a method or a function. Delegate class has a signature and it can only reference those methods whose signature is compliant with the class. Delegates are type-safe functions pointers or callbacks.
Below is a sample code which shows a example of how to implement delegates.
Delegate is a class that can hold a reference to a method or a function. Delegate class has a signature and it can only reference those methods whose signature is compliant with the class. Delegates are type-safe functions pointers or callbacks.
Below is a sample code which shows a example of how to implement delegates.
Public Class FrmDelegates
Inherits System.Windows.Forms.Form
Public Delegate Sub DelegateAddString()
Private Sub FrmDelegates_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub AddString()
lstDelegates.Items.Add(“Running AddString() method”)
End Sub
Private Sub cmdDelegates_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles cmdDelegates. Click
Dim objDelegateAddString As DelegateAddString
objDelegateAddString = AddressOf AddString
objDelegateAddString.Invoke()
End Sub
End Class
Inherits System.Windows.Forms.Form
Public Delegate Sub DelegateAddString()
Private Sub FrmDelegates_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub AddString()
lstDelegates.Items.Add(“Running AddString() method”)
End Sub
Private Sub cmdDelegates_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles cmdDelegates. Click
Dim objDelegateAddString As DelegateAddString
objDelegateAddString = AddressOf AddString
objDelegateAddString.Invoke()
End Sub
End Class
In
the above there is a method called “AddString()” which adds a string to a
listbox.You can also see a delegate declared as :
Public Delegate Sub DelegateAddString()
This delegate signature is compatible with the “AddString” method. When I mean compatibility that means that there return types and passing parameter types are same.
Later in command click of the button object of the Delegate is created and the method pointer is received from “AddressOf ” keyword.
Then by using the “Invoke” method the method is invoked.
Public Delegate Sub DelegateAddString()
This delegate signature is compatible with the “AddString” method. When I mean compatibility that means that there return types and passing parameter types are same.
Later in command click of the button object of the Delegate is created and the method pointer is received from “AddressOf ” keyword.
Then by using the “Invoke” method the method is invoked.
Figure:: Deligate in Action
63.What are events ?
As compared to delegates events works with source and listener methodology. So listeners who are interested in receiving some events they subscribe to the source. Once this subscription is done the source raises events to its entire listener when needed. One source can have multiple listeners.
In sample given below class “ClsWithEvents” is a event source class, which has a event “EventAddString()”. Now the listeners who are interested in receiving this events they can subscribe to this event. In class “FrmWithEvents” you can see they handle clause which is associated with the “mobjClsWithEvents” objects.
63.What are events ?
As compared to delegates events works with source and listener methodology. So listeners who are interested in receiving some events they subscribe to the source. Once this subscription is done the source raises events to its entire listener when needed. One source can have multiple listeners.
In sample given below class “ClsWithEvents” is a event source class, which has a event “EventAddString()”. Now the listeners who are interested in receiving this events they can subscribe to this event. In class “FrmWithEvents” you can see they handle clause which is associated with the “mobjClsWithEvents” objects.
Public Class ClsWithEvents
Event EventAddString(ByVal Value As String)
Public Sub AddString()
RaiseEvent EventAddString(“String added by Event”)
End Sub
End Class
Public Class FrmWithEvents
Inherits System.Windows.Forms.Form
Private WithEvents mobjClsWithEvents As New ClsWithEvents()
Private Sub FrmWithEvents_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub mobjClsWithEvents_EventAddString(ByVal Value As
String) Handles mobjClsWithEvents.EventAddString
LstData.Items.Add(Value)
End Sub
Private Sub CmdRunEvents_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles CmdRunEvents.Click
mobjClsWithEvents.AddString()
End Sub
End Class
Event EventAddString(ByVal Value As String)
Public Sub AddString()
RaiseEvent EventAddString(“String added by Event”)
End Sub
End Class
Public Class FrmWithEvents
Inherits System.Windows.Forms.Form
Private WithEvents mobjClsWithEvents As New ClsWithEvents()
Private Sub FrmWithEvents_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub mobjClsWithEvents_EventAddString(ByVal Value As
String) Handles mobjClsWithEvents.EventAddString
LstData.Items.Add(Value)
End Sub
Private Sub CmdRunEvents_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles CmdRunEvents.Click
mobjClsWithEvents.AddString()
End Sub
End Class
Fig:
Events In Action
64.Do events have return type ?
No, events do not have return type.
65. Can event’s have access modifiers ?
Event’s are always public as they are meant to serve every one register ing to it. But you can access modifiers in events.You can have events with protected keyword which will be accessible only to inherited classes.You can have private events only for object in that class.
66.What is shadowing ?
When two elements in a program have same name, one of them can hide and shadow the other one. So in such cases the element which shadowed the main element is referenced.
Below is a sample code, there are two classes “ClsParent” and “ClsShadowedParent”. In “ClsParent” there is a variable “x” which is a integer.
“ClsShadowedParent” overrides “ClsParent” and shadows the “x” variable to a string.
Note:- In Sample CD “WindowsShadowing” is folder which has the sample code. If you run the program you can have two output’s one which shows a integer and other which shows a string.
64.Do events have return type ?
No, events do not have return type.
65. Can event’s have access modifiers ?
Event’s are always public as they are meant to serve every one register ing to it. But you can access modifiers in events.You can have events with protected keyword which will be accessible only to inherited classes.You can have private events only for object in that class.
66.What is shadowing ?
When two elements in a program have same name, one of them can hide and shadow the other one. So in such cases the element which shadowed the main element is referenced.
Below is a sample code, there are two classes “ClsParent” and “ClsShadowedParent”. In “ClsParent” there is a variable “x” which is a integer.
“ClsShadowedParent” overrides “ClsParent” and shadows the “x” variable to a string.
Note:- In Sample CD “WindowsShadowing” is folder which has the sample code. If you run the program you can have two output’s one which shows a integer and other which shows a string.
Public Class ClsParent
Public x As Integer
End Class
Public Class ClsShadowedParent
Inherits ClsParent
Public Shadows x As String
End Class
Public x As Integer
End Class
Public Class ClsShadowedParent
Inherits ClsParent
Public Shadows x As String
End Class
Figure: Shadowing
in Action
67.What is the difference between Shadowing and Overriding ?
Following are the differences between shadowing and overriding :-
67.What is the difference between Shadowing and Overriding ?
Following are the differences between shadowing and overriding :-
- Overriding redefines only the implementation while shadowing redefines the whole element.
- In overriding derived classes can refer the parent class element by using “ME” keyword, but in shadowing you can access it by “MYBASE”.
68.What is the difference between delegate and events?
- Actually events use delegates in bottom. But they add an extra layer on the delegates, thus forming the publisher and subscriber model.
- As delegates are function to pointers they can move across any clients. So any of the clients can add or remove events, which can be pretty confusing. But events give the extra protection by adding the layer and making it a publisher and subscriber model.
69.If we inherit a class do the private variables also get
inherited ?
Yes, the variables are inherited but can not be accessed directly by the class interface.
70.What are the different accessibility levels defined in .NET?
Following are the five levels of access modifiers :-
Yes, the variables are inherited but can not be accessed directly by the class interface.
70.What are the different accessibility levels defined in .NET?
Following are the five levels of access modifiers :-
- Private : Only members of class have access.
- Protected :-All members in current class and in derived classes can access the variables.
- Friend (internal in C#) :- Only members in current project have access to the elements.
- Protected friend (protected internal in C#) :- All members in current project and all members in derived class can access the variables.
- Public :- All members have access in all classes and projects.
71.What are similarities between Class and structure ?
Following are the similarities between classes and structures :-
Following are the similarities between classes and structures :-
- Both can have constructors, methods, properties, fields, constants,enumerations, events, and event handlers.
- Structures and classes can implement interface.
- Both of them can have constructors with and without parameter.
- Both can have delegates and events.
72.What is the difference between Class and structure’s ?
Following
are the key differences between them :-
- Structure are value types and classes are reference types. So structures use stack and classes use heap.
- Structures members can not be declared as protected, but class members can be. You can not do inheritance in structures.
- Structures do not require constructors while classes require.
- Objects created from classes are terminated using Garbage collector. Structures are not destroyed using GC.
73.What is Dispose method in .NET ?
.NET provides “Finalize” method in which we can clean up our resources. But relying on this is not always good so the best is to implement “Idisposable” interface and implement the “Dispose” method where you can put your clean up routines.
74.What is the use of “OverRides” and “Overridable”keywords ?
Overridable is used in parent class to indicate that a method can be overridden. Overrides is used in the child class to indicate that you are overriding a method.
75.Where are all .NET Collection classes located ?
System.Collection namespace has all the collection classes available in .NET.
76. What is ArrayList ?
Array is whose size can increase and decrease dynamically. Array list can hold item of different types. As Array list can increase and decrease size dynamically you do not have to use the REDIM keyword. You can access any item in array using the INDEX value of the array position.
77. What’s a HashTable ?
You can access array using INDEX value of array, but how many times you know the real value of index. Hashtable provides way of accessing the index using a user identified KEY value, thus removing the INDEX problem.
78. What are queues and stacks ?
Queue is for first-in, first-out (FIFO) structures. Stack is for last-in, first-out (LIFO)structures.
79. What is ENUM ?
It’s used to define constants.
80.What is nested Classes ?
Nested classes are classes within classes. In sample below “ClsNested” class has a “ChildNested”
.NET provides “Finalize” method in which we can clean up our resources. But relying on this is not always good so the best is to implement “Idisposable” interface and implement the “Dispose” method where you can put your clean up routines.
74.What is the use of “OverRides” and “Overridable”keywords ?
Overridable is used in parent class to indicate that a method can be overridden. Overrides is used in the child class to indicate that you are overriding a method.
75.Where are all .NET Collection classes located ?
System.Collection namespace has all the collection classes available in .NET.
76. What is ArrayList ?
Array is whose size can increase and decrease dynamically. Array list can hold item of different types. As Array list can increase and decrease size dynamically you do not have to use the REDIM keyword. You can access any item in array using the INDEX value of the array position.
77. What’s a HashTable ?
You can access array using INDEX value of array, but how many times you know the real value of index. Hashtable provides way of accessing the index using a user identified KEY value, thus removing the INDEX problem.
78. What are queues and stacks ?
Queue is for first-in, first-out (FIFO) structures. Stack is for last-in, first-out (LIFO)structures.
79. What is ENUM ?
It’s used to define constants.
80.What is nested Classes ?
Nested classes are classes within classes. In sample below “ClsNested” class has a “ChildNested”
class nested inside it.
Public Class ClsNested
Public Class ChildNested
Public Sub ShowMessage()
MessageBox.Show(“Hi this is nested class”)
End Sub
End Class
End Class
Public Class ClsNested
Public Class ChildNested
Public Sub ShowMessage()
MessageBox.Show(“Hi this is nested class”)
End Sub
End Class
End Class
This
is the way we can instantiate the nested class and make the method call.
Dim pobjChildNested As New ClsNested.ChildNested()
pobjChildNested.ShowMessage()
81.In what instances you will declare a constructor to be private?
When we create a private constructor, we can not create object of the class directly from a client. So you will use private constructors when you do not want instances of the class to be created by any external client. Example UTILITY functions in project will have no instance and be used with out creating instance, as creating instances of the class would be waste of memory.
82.Can we have different access modifiers on get/set methods of a property ?
No we can not have different modifiers same property. The access modifier on a property applies to both its get and set accessors.
83.If we write a goto or a return statement in try and catch block will the finally block execute ?
The code in then finally always run even if there are statements like goto or a return statements.
84.What is Indexer ?
An indexer is a member that enables an object to be indexed in the same way as an array.
85.Can two catch blocks be executed?
No, once the proper catch section is executed the control goes finally to block. So there will not be any scenarios in which multiple catch blocks will be executed.
86.What is the difference between System.String and System.StringBuilder classes?
System.String is immutable; System.StringBuilder can have mutable string where a variety of operations can be performed.
87.Describe the accessibility modifier “protected internal”?
It is available to classes that are within the same assembly and derived from the specified base class.
88.What does the term immutable mean?
The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.
89.What’s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.
90.What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.
91.What’s the advantage of using System.Text.StringBuilder over System.String?
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.
92.What’s a 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.
93.What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.
94.Which one is trusted and which one is untrusted?
Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.
95.What is a pre-requisite for connection pooling?
Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.
96.Does C# replace C++?
There are three options open to the Windows developer from a C++ background:
•Stick with standard C++. Don't use .NET at all.
•Use C++ with .NET. Microsoft supply a .NET C++ compiler that produces IL rather than machine code. However to make full use of the .NET environment (e.g. garbage collection), a set of extensions are required to standard C++. In .NET 1.x this extended language is called Managed Extensions for C++. In .NET 2.0 ME C++ has been completely redesigned under the stewardship of Stan Lippman, and renamed C++/CLI.
•Forget C++ and use C#.
Each of these options has merits, depending on the developer and the application. For my own part, I intend to use C# where possible, falling back to C++ only where necessary. ME C++ (soon to be C++/CLI) is very useful for interop between new .NET code and old C++ code - simply write a managed wrapper class using ME C++, then use the managed class from C#. From experience, this works well.
97.So I can pass an instance of a value type to a method that takes an object as a parameter?
Yes. For example:
Dim pobjChildNested As New ClsNested.ChildNested()
pobjChildNested.ShowMessage()
81.In what instances you will declare a constructor to be private?
When we create a private constructor, we can not create object of the class directly from a client. So you will use private constructors when you do not want instances of the class to be created by any external client. Example UTILITY functions in project will have no instance and be used with out creating instance, as creating instances of the class would be waste of memory.
82.Can we have different access modifiers on get/set methods of a property ?
No we can not have different modifiers same property. The access modifier on a property applies to both its get and set accessors.
83.If we write a goto or a return statement in try and catch block will the finally block execute ?
The code in then finally always run even if there are statements like goto or a return statements.
84.What is Indexer ?
An indexer is a member that enables an object to be indexed in the same way as an array.
85.Can two catch blocks be executed?
No, once the proper catch section is executed the control goes finally to block. So there will not be any scenarios in which multiple catch blocks will be executed.
86.What is the difference between System.String and System.StringBuilder classes?
System.String is immutable; System.StringBuilder can have mutable string where a variety of operations can be performed.
87.Describe the accessibility modifier “protected internal”?
It is available to classes that are within the same assembly and derived from the specified base class.
88.What does the term immutable mean?
The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.
89.What’s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.
90.What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.
91.What’s the advantage of using System.Text.StringBuilder over System.String?
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.
92.What’s a 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.
93.What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.
94.Which one is trusted and which one is untrusted?
Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.
95.What is a pre-requisite for connection pooling?
Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.
96.Does C# replace C++?
There are three options open to the Windows developer from a C++ background:
•Stick with standard C++. Don't use .NET at all.
•Use C++ with .NET. Microsoft supply a .NET C++ compiler that produces IL rather than machine code. However to make full use of the .NET environment (e.g. garbage collection), a set of extensions are required to standard C++. In .NET 1.x this extended language is called Managed Extensions for C++. In .NET 2.0 ME C++ has been completely redesigned under the stewardship of Stan Lippman, and renamed C++/CLI.
•Forget C++ and use C#.
Each of these options has merits, depending on the developer and the application. For my own part, I intend to use C# where possible, falling back to C++ only where necessary. ME C++ (soon to be C++/CLI) is very useful for interop between new .NET code and old C++ code - simply write a managed wrapper class using ME C++, then use the managed class from C#. From experience, this works well.
97.So I can pass an instance of a value type to a method that takes an object as a parameter?
Yes. For example:
class
CApplication
{
public static void Main()
{
int x = 25;
string s = "fred";
DisplayMe( x );
DisplayMe( s );
}
static void DisplayMe( object o )
{
System.Console.WriteLine( "You are {0}", o );
}
}
This would display:
You are 25
You are fred
{
public static void Main()
{
int x = 25;
string s = "fred";
DisplayMe( x );
DisplayMe( s );
}
static void DisplayMe( object o )
{
System.Console.WriteLine( "You are {0}", o );
}
}
This would display:
You are 25
You are fred
98.Does the System.Exception class have any cool features?
Yes - the feature which stands out is the StackTrace property. This provides a call stack which records where the exception was thrown from.
For example, the following code:
using System;
class CApp
{
public static void Main()
{
try
{
f();
}
catch( Exception e )
{
Console.WriteLine("System.Exception stack trace=\n{0}", e.StackTrace );
}
}
static void f()
{
throw new Exception( "f went pear-shaped" );
}
}
produces this output:
System.Exception stack trace =
at CApp.f()
at CApp.Main()
class CApp
{
public static void Main()
{
try
{
f();
}
catch( Exception e )
{
Console.WriteLine("System.Exception stack trace=\n{0}", e.StackTrace );
}
}
static void f()
{
throw new Exception( "f went pear-shaped" );
}
}
produces this output:
System.Exception stack trace =
at CApp.f()
at CApp.Main()
Note:
however,
that this stack trace was produced from a debug build. A release build may
optimise away some of the method calls which could mean that the call
stack isn't quite what you expect.
99.How can I check the type of an object at runtime?
You can use the is keyword. For example:
99.How can I check the type of an object at runtime?
You can use the is keyword. For example:
using System;
class CApp
{
public static void Main()
{
string s = "fred";
long i = 10;
Console.WriteLine("{0} is {1}an integer",s,(IsInteger(s)? "" :"not") );
Console.WriteLine("{0} is {1}an integer",i,(IsInteger(i)? "" :"not") );
}
static bool IsInteger( object obj )
{
if( obj is int || obj is long )
return true;
else
return false;
}
}
produces the output:
fred is not an integer
10 is an integer.
class CApp
{
public static void Main()
{
string s = "fred";
long i = 10;
Console.WriteLine("{0} is {1}an integer",s,(IsInteger(s)? "" :"not") );
Console.WriteLine("{0} is {1}an integer",i,(IsInteger(i)? "" :"not") );
}
static bool IsInteger( object obj )
{
if( obj is int || obj is long )
return true;
else
return false;
}
}
produces the output:
fred is not an integer
10 is an integer.
100.Can I get
the name of a type at runtime?
Yes,
use the GetType method of the object class (which all types inherit from). For
example:
using System;
class CTest
{
class CApp
{
public static void Main()
{
long i = 10;
CTest ctest = new CTest();
DisplayTypeInfo( ctest );
DisplayTypeInfo( i );
}
static void DisplayTypeInfo( object obj )
{
Console.WriteLine("Type name={0}, full type name={1}", obj.GetType(),
class CTest
{
class CApp
{
public static void Main()
{
long i = 10;
CTest ctest = new CTest();
DisplayTypeInfo( ctest );
DisplayTypeInfo( i );
}
static void DisplayTypeInfo( object obj )
{
Console.WriteLine("Type name={0}, full type name={1}", obj.GetType(),
obj.GetType().FullName );
}
}
}
}
}
produces the following output:
Type name = CTest, full type name = CTest
Type name = Int64, full type name = System.Int64
produces the following output:
Type name = CTest, full type name = CTest
Type name = Int64, full type name = System.Int64
0 comments:
Post a Comment