Beruflich Dokumente
Kultur Dokumente
A constructor is a member function that has the same name as the class name and is invoked
automatically when the class is instantiated. A constructor is used to provide initialization code
that gets executed every time the class is instantiated.
A protected constructor can only be invoked from the subclasses of the class in which it is
defined. This is illustrated in the example that follows.
Listing 5
using system;
class B
{
protected B (string s) {}
}
class D : B
{
public D () : base ("Called from D class") {}
}
class E
{
public static void Main(string []args)
{
B x = new B ("Called from E class");
/*Error. The constructor test.B.B(string s) is inaccessible due to its
protection level*/
}
}
Constructor Overloading
A constructor can take zero or more arguments as parameters. A constructor with zero arguments
is known as the default constructor. We can have multiple constructors in a class with different
sets of signatures. Such constructors are known as “overloaded constructors”. The overloaded
constructors of a class must differ in their number of arguments, type of arguments, and/or order
of arguments. This gives the user the ability to initialize the object in multiple ways.
The class in the program shown below contains three constructors. The first is the default
constructor, followed by the two argument constructors. Note that the constructors differ in their
signature.
Listing 6: Overloaded Constructors
using system;
public class Test
{
public Test()
{
//Default constructor
}
public Test(int sampleValue)
{
// This is the constructor with one parameter.
}
public Test(int firstValue, int secondValue)
{
// This is the constructor with two parameters.
}
}
Constructor Chaining
Constructor chaining refers to the ability of a class to call one constructor from another
constructor. In order to call one constructor from another, we use base (parameters) or : this
(parameters) just before the actual code for the constructor, depending on whether we want to
call a constructor in the base class or in the current class.
Listing 7: Constructor Chaining
using system;
public class Test
{
public Test(): this(10)
{
// This is the default constructor
}
public Test(int firstValue)
{
// This is the constructor with one parameter.
}
}
public Base(int x)
{
Console.WriteLine("Base Constructor Version 2");
}
}
class MyClient
{
public static void Main()
{
Derived dObject = new Derived();
//Displays 'Base Constructor Version 2' followed by 'Derived Constructor'.
}
}
Constructors are executed in the order of inheritance as shown in the example below.
Listing 9: Order of Execution of Constructors in Inheritance
using System;
class Base
{
public Base()
{
Console.WriteLine("Base constructor");
}
}
class Derived : Base
{
public Derived()
{
Console.WriteLine("Derived constructor");
}
}
class Test
{
public static void Main()
{
Derived dObject = new Derived();
//Displays 'Base constructor' followed by 'Derived constructor'.
}
}
It is not possible to inherit a class that has only a private constructor.
Listing 10: Private Constructors Prevent Inheritance
using system;
class Base
{
Base( )
{
}
}
class Derived : Base // Syntax Error.
{
public static void Main()
{
Derived dObject = new Derived ();
}
}
Conclusion
The best practice is to always explicitly specify the constructor, even if it is a public default
constructor. Proper design of constructors goes a long way in solving the challenges faced in
class designs.
C# Delegates Explained
A delegate is an object that refers to a static method or an instance method
A delegate is an object that is created to refer to a static method or an instance method, and then
used to call this method. To start off, you create a new delegate type in a different way than you
create any other class. You use the delegate keyword as in the following statement.
public delegate int DelegateToMethod(int x, int y);
The First Delegate Example
using System;
namespace Delegates
{
public delegate int DelegateToMethod(int x, int y);
}
}
Multicast Delegates
A multicast delegate is an object that maintains a linked list of delegates. Invoking the delegate
invokes each delegate (which in turn calls its encapsulated method) in the same order that it has
been added to the linked list. In our example we have created an object (a delegate) called
multiDelegate of type Math.DelegateToMethod and assigned a null value to this object.
using System;
namespace Delegates
{
public class Math
{
// note that the delegate now is a nested type of the Math class
public delegate void DelegateToMethod(int x, int y);
==, !=, <, >, <= , >= All relational operators can be overloaded,
but only as pairs.
=, . , ?:, ->, new, is, as, sizeof These operators can't be overloaded
In C#, a special function called operator function is used for overloading purpose. These special
function or method must be public and static. They can take only value arguments. The ref and
out parameters are not allowed as arguments to operator functions.
The general form of an operator function is as follows.
public static return_type operator op (argument list)
Where the op is the operator to be overloaded and operator is the required keyword. For
overloading the unary operators, there is only one argument and for overloading a binary operator
there are two arguments. Remember that at least one of the arguments must be a user-defined
type such as class or struct type.
Overloading Unary Operators The general form of operator function for unary operators is as
follows. public static return_type operator op (Type t) { // Statements } Where Type must be a
class or struct. The return type can be any type except void for unary operators like +, ~, ! and dot
(.). but the return type must be the type of 'Type' for ++ and o remember that the true and false
operators can be overloaded only as pairs. The compilation error occurs if a class declares one of
these operators without declaring the other.
The following program overloads the unary - operator inside the class Complex
// Unary operator overloading
using System;
class Complex
{
private int x;
private int y;
public Complex()
{
}
public Complex(int i, int j)
{
x = i;
y = j;
}
public void ShowXY()
{
Console.WriteLine(\"{0} {1}\",x,y);
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10,20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex();
c2.ShowXY(); // displays 0 & 0
c2 = -c1;
c2.ShowXY(); // diapls -10 & -20
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10,20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex(20,30);
c2.ShowXY(); // displays 20 & 30
Complex c3 = new Complex();
c3 = c1 + c2;
c3.ShowXY(); // dislplays 30 & 50
}
}
The binary operators such as = =, ! =, <, >, < =, > = can be overloaded only as pairs. Remember
that when a binary arithmetic operator is overloaded, corresponding assignment operators also
get overloaded automatically. For example if we overload + operator, it implicitly overloads the + =
operator also.
Summary
1.The user defined operator declarations can't modify the syntax, precedence or associativity of
an operator. For example, a + operator is always a binary operator having a predefined
precedence and an associativity of left to right.
2.User defined operator implementations are given preference over predefined implementations.
3.Operator overload methods can't return void.
4.The operator overload methods can be overloaded just like any other methods in C#. The
overloaded methods should differ in their type of arguments and/or number of arguments and/or
order of arguments. Remember that in this case also the return type is not considered as part of
the method signature.
// calculate factorial
Or
private bool CheckPalindrome(string myString)
{
string strrevs="";
foreach char c in myString
{
strrevs= c + strrevs;
}
if (strrevs==myString)
return true;
else
return false;
}
Enable ViewState turns on the automatic state management
feature that enables server controls to re-populate their
values on a round trip without requiring you to write any
code.
What are validator? Name the Validation controls in asp.net? How do u disable
them? Answer
#1
Validator means checking inputed data in any field like
textBox or dropdownbox any other which we want to validate
at client side using sever tag.
<%
Response.Cookies("username") = "you"
Response.Cookies("username").Expires = Date.MaxValue
%>
how can u display multi language (i.e english,spanish...) web site? Answer
#2
Create resource files for each language.. u want to dispaly
on the website.(add+new item+resource file)
now panel1.innerhtml=resourcemanager1.string;
and so on...
0
Nirakar
Re: How to find the client browser type ? Answer
#2
we can identify the browser name using javascript
0
Swapna
Re: How many types of session in asp.net2.0 Answer
#2
three types of session states in asp.net
InProc
OutProc
SqlServer
what is the differance between native code & managed code? Answer
# 2 native code is cpu dependent and managed code target to clr
0
Pramod
Re: If cookies is disabled in client browser will session work ? Answer
#2
Sessions are normally tracked with cookies. However,
clients are not required to accept cookies. Furthermore,
you can turn off the use of cookies for session tracking
altogether in the Web Application Server Control Panel.
However when cookies are turned off or cookies are not
enabled on a specific client computer, the server must work
harder to track the session state, which has a performance
impact. The recommendation is to leave cookies on and let
the server automatically fall back to the cookieless
operation only when required by a specific client
connection.
How do you pass session values from one page to another ? Answer
#1
1.In first page set session variable. e.g.
string myName=Session["Name"].ToString();
What is the difference between session state and session variables ? Answer
#1
Session state is used to store session specific information
for a website.
session variable store infomation between http request for
a particular user.
response.PayAnyonePaymentDetails[0].IsQueueNumberNull()
What is JIT, what are types of JITS and their purpose ? Answer
#1
JIT is Just in Time compiler which compiles the MSIL into
NAtive code. there are 2 types of JITS.
0
03/05/2007
Re: What is JIT, what are types of JITS and their purpose ? Answer
#2
There are three types of JIT copilers.
0
Mouli
Re: What is CTS, CLS and CLR ? Answer
#2
CLR
this is common language runtime.the code which is in
environment of clr is called managed code.every language
has runtime in case of .net there is CLR.so that that has
some responsibilites that is to tack care of the execution
of code
other responsibilites
garbage collection-in that it remove the object which are
not refered for long time.using Idisposable interface with
dispose method
Cls
common language spefication
thsi is guideline that to communicate smoothly with other
CTS
common type system
this is used to communicate with other language.
example in vb we have int and in c++ we have long so that
in one case they are not compatiable with each other so
that CTS palys important role with using System.int32
How do you set language in web.cofig ? Answer
#1
? To set the UI culture and culture for all pages, add a
globalization section to the Web.config file, and then set
the uiculture and culture attributes, as shown in the
following example:
<globalization uiculture="es" culture="es-MX" />
? To set the UI culture and culture for an individual page,
set the Culture and UICulture attributes of the @ Page
directive, as shown in the following example:
<%@ Page UICulture="es" Culture="es-MX" %>
0
Deepak Kumar Srivastava
Re: How many web.config a application can have ? Answer
#2
You can have a single web.config file per project.It exists
at the root folder of the project.
Regards
0
Sridhara Krishna
Re: Tell About Global.asax ? Answer
#2
it allows to execute application level events and set
application level variables.
0
Ansu_kumar
Re: How do you retrieve information from web.config ? Answer
#2
In web.congig you can add key and its value.And that key
value u can retrive like
string connectionString =
System.Configuration.ConfigurationSettings.AppSettings
["conStringWeb"].ToString()
0
Raj
Re: Does the following statement executes successfully: Response.Write(?value of
i = ? + i); Answer
#2
if you would have declared and assigned some value to the
variable "i" then it will execute.
In a page u have Web user controls . So what is the order in which the Page life
Cycles takes place? Answer
#1
order of events are
init
page load
control load
page unload
How to write unmanaged code and how to identify whether the code is managed /
unmanaged ? Answer
#1
you can only write unmanaged code in c# not in vb.net
you can only call unmanaged code in vb.net. calling and
writing unmanaged code are different things.
web.config
Web.config is a security in ASP.Net application and how to
secure applications. Web.config does most of the work for
the application the who, what, where, when and how to be
authenticated.
1.This is automatically created when you create an ASP.Net
web application project.
2.This is also called application level configuration file.
3.This file inherits setting from the machine.config
what are the new server controls added in Asp.net 2.0? Answer
#1
Navigation Controls:
Site MapPath
TreeView
Menu
DataBindingControls
SqlDataSource
oledbDatasource
ObjectDataSource
DataCotrols:
GridView
DetailsView
FormsView
that uses table named tabl1 and tabl2 etc..but actually not
exists in database is allowed
value at a time.
5. We can call the functions in sql statements (select max
(sal) from emp). where as sp is
not so
6. Function do not return the images,text whereas sp
returns all.
7. Function and sp both can return the values. But function
returns 1 value only.
procedure can return multiple values(max. 1024) we can
select the fields from function. in
business logic
9. Functions MUST return a value, procedures need not be.
10. You can have DML(insert, update, delete) statements in
a function. But, you cannot call
How Web Services help Us? What r the difference between Remoting and
webservices Answer
#1
HI!!
0
Hari Ganesh. V
Re: How Web Services help Us? What r the difference between Remoting and
webservices Answer
#2
In remoting objects communicates thru homogineous protocols
i.e.,TCP.Where as Webservices provides funtionality thru
hetrogenious protocals i.e., HTTP,SOAP.
If we add a textbox and give the required field validator,and i add two radio buttons
1 is yes another one is No.And i add another one server control button ,if i click the
button ,if the radio button Yes is checked the validation control is fired ,if no the
validation control is not fired.So what you used to solve this problem. Answer
#2
Hi,
We can add the code in page_load
One Listbox showing all cities. If you select one city in list box the information
related to that particular city should be displayed in Datagrid . How do you do that?
Answer
#2
protected void ddlcity_SelectedIndexChanged(object sender,
EventArgs e)
{
sqlConnection con= new sqlConnection(" ");
string str="select * from table where city ='" +
ddlcity.SelectItem.Text ="'";
sqlDataAdapter da= new slqDataAdapter(str,con)
dataset ds = new dataset;
da.fill(ds,"City");
dgview.datasource=ds.tables["City"];
dgview.dataBind();
}
}
catch
{
}
}
}
What is CSS? What is the advantage os using CSS in ASP.NET Web Applications?
Answer
#2
CSS stands for Cascading Style Sheets. CSS is used to give
a feel and look to the web pages, which will be unique
throughout the application. In other words it's just like a
thin layer above the webpage to give the web page a good
appearance.
What is the difference between User Controls and Master Pages Answer
#1
Both are code reduce features and reusability Purpose.When
we create Masterpage that is common to overall
project,whereas user controls these r used when we have
requirement on specific criteria.
Master page ex: INBOX,SPAM,DRAFT,TRASH etc in YAHOO WEBSITE
0
Venkatesh
Re: What is the difference between User Controls and Master Pages Answer
#2
Master pages and user controils are two different concepts.
What is difference b/w Data Grid in ASP.Net 1.1 and Gridview in 2.0 Answer
#1
Gridview is the replacement in .net 2.0 for the datagrid.
the differences between them is >>sorting editing and
paging are the additional capabilities in gridview which
requires no coding while Datgrid requires the user
coding .Gridview has improved databinding using smart
tag.Additional column types and design time column
operations.Customised pager UI using pager
template.Customized paging support.
0
Vdk
Re: What is difference b/w Data Grid in ASP.Net 1.1 and Gridview in 2.0 Answer
#2
Datagrid has itemdatabound event but in gridview it is
replaced by rowdatabound.In datagrid u can show more than
one table with their relation while not possible in
gridview.
0
Ajit
Re: How many webforms are possible on a single webpage? Answer
#2
n number of pages we can...
Dategrid filtering and sorting How can we sort all the fields at once? Answer
#2
Undoubtedly u need to write a sql query for this with the
order by (or) sort by.
And also call the subroutine that fills the datagrid after
each insert or delete so that u can see the changes at the
runtime with the new alignment(i mean sorting)...