How to create an instance of a class in c#?
To create an instance of a class in C#, you use the new
keyword.
Example:
public class Dog
{
public string Name { get; set; }
}
Dog myDog = new Dog();
myDog.Name = "Rex";
Solution:
Make use of constructors for better object initialization:
public class Dog
{
public string Name { get; set; }
public Dog(string name)
{
Name = name;
}
}
Dog myDog = new Dog("Rex");