Understanding Constructors in C#
Sandeep Pal
9+ Exp | C# | Dotnet Core | Web API | MVC 5 | Azure | React Js | Node JS | Microservices | Sql | MySQL | JavaScript | UnitTest | Dapper | Linq | DSA | Entity framework Core | Web Forms | Jquery | MongoDB | Quick Learner
?? Understanding Constructors in C# ??
In C#, constructors are special methods used to initialize objects. They are called when an instance of a class is created and can set default values, allocate resources, or perform any setup required. Let’s explore the different types of constructors:
Default Constructor:
public class Person
{
public string Name { get; set; }
// Default constructor
public Person()
{
Name = "Unknown";
}
}
// Usage
Person person = new Person();
Console.WriteLine(person.Name); // Output: Unknown
Parameterized Constructor:
public class Person
{
public string Name { get; set; }
// Parameterized constructor
public Person(string name)
{
Name = name;
}
}
// Usage
Person person = new Person("Alice");
Console.WriteLine(person.Name); // Output: Alice
Static Constructor:
领英推荐
public class Configuration
{
public static string AppName { get; }
// Static constructor
static Configuration()
{
AppName = "My Application";
}
}
// Usage
Console.WriteLine(Configuration.AppName); // Output: My Application
Copy Constructor:
public class Person
{
public string Name { get; set; }
// Copy constructor
public Person(Person other)
{
Name = other.Name;
}
}
// Usage
Person original = new Person("Bob");
Person copy = new Person(original);
Console.WriteLine(copy.Name); // Output: Bob
??? When to Use Constructors:
Understanding constructors is key to mastering object-oriented programming in C#. Happy coding! ???
#CSharp #Programming #ObjectOriented #Coding #SoftwareDevelopment #TechTips