Rodia
0
Q:

c# class constructor

public class Person
{
   private string last;
   private string first;

   public Person(string lastName, string firstName)
   {
      last = lastName;
      first = firstName;
   }

   // Remaining implementation of Person class.
}
10
//The Class
public class MyClass
{
  	//Some Variables
	public readonly int var1;
  	public readonly string var2;
  	//readonly only lets you set it ina constructor	
  
  	//The Constructor (public [class name](parameters))
  	public MyClass(int param1, string param2)
    {
      	//Setting the earlier variables
     	var1 = param1;
      	var2 = param2;
    }
}

//Creating an object using that class
MyClass Class1 = new MyClass(10, "Hello, World!");
MyClass Class2 = new MyClass(9999, "This is the second object!");

Console.WriteLine(Class1.var1);
Console.WriteLine(Class2.var2);

//Output
//10
//This is the second object!
2
// Create a Car class
class Car
{
  public string model;  // Create a field

  // Create a class constructor for the Car class
  public Car()
  {
    model = "Mustang"; // Set the initial value for model
  }

  static void Main(string[] args)
  {
    Car Ford = new Car();  // Create an object of the Car Class (this will call the constructor)
    Console.WriteLine(Ford.model);  // Print the value of model
  }
}

// Outputs "Mustang"
 
0

New to Communities?

Join the community