create an instance of a class with a constructor in csharp

To create an instance of a class with a constructor in C#, you need to follow these steps:

  1. Define a class with a constructor that takes one or more parameters.
main.cs
public class MyClass 
{
    public MyClass(string name, int age) 
    {
        Name = name;
        Age = age;
    }

    public string Name { get; set; }
    public int Age { get; set; }
}
191 chars
12 lines
  1. Create an instance of the class using the "new" keyword, and pass in the constructor parameters.
main.cs
MyClass myObject = new MyClass("John", 25);
44 chars
2 lines
  1. Access the properties and methods of the object using the dot notation.
main.cs
Console.WriteLine($"Name: {myObject.Name}"); // Output: Name: John
Console.WriteLine($"Age: {myObject.Age}"); // Output: Age: 25
129 chars
3 lines

In the example above, we created an instance of the MyClass class by passing in the name and age parameters to the constructor. We can then access the properties of the object using the dot notation.

gistlibby LogSnag