Introduction:
Here I will explain what is copy constructor in c# with example. Copy constructor in c# is used to create new instance to the values of an existing instance.
Description:
In
previous posts I explained create captcha with refresh button in asp.net, use
of virtual, override and new keyword with examples in c#, method overloading and overriding, delegates example in c#, sealed class in c#, using statement in c#, OOPS examples in c# and many articles
relating to
interview questions in c#,
asp.net,
SQL server, JavaScript,
jQuery. Now I will explain copy
constructor in c#.net with example.
Constructor
is a special method of a class which will invoke automatically whenever
instance or object of class is created. Constructors are responsible for object
initialization and memory allocation of its class. If we create any class
without constructor, the compiler will automatically create one default constructor
for that class. There is always at least one constructor in every class. To
know more about constructors
check this link Constructors in c# with example.
Copy Constructor
A parameterized
constructor that contains a parameter of same class type is called as copy
constructor. Main purpose of copy constructor is to initialize new instance to
the values of an existing instance. Check below example for this
using System;
namespace ConsoleApplication3
{
class Sample
{
public string
param1, param2;
public Sample(string
x, string y)
{
param1 = x;
param2 = y;
}
public Sample(Sample
obj) //
Copy Constructor
{
param1 = obj.param1;
param2 = obj.param2;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample("Welcome",
"Aspdotnet-Suresh"); // Create
instance to class Sample
Sample obj1=new Sample(obj); // Here
obj details will copied to obj1
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}
}
|
When
we run above program it will show output like as shown below
Output
Welcome
to Aspdotnet-Suresh
|
I hope it helps you to know about copy constructor. If you
want to read more about constructors check this link Constructors in c# with example
If you enjoyed this post, please support the blog below. It's FREE! Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email. |
|||
|
|||
1 comments :
Nic..!!
Note: Only a member of this blog may post a comment.