Static() inside Structures C#

Static Function inside structures in C# :-

Program 1:-

using System;
struct Employee
{
public int EmpId;
public string FirstName;
public string LastName;

public static void static_func()
{
Console.WriteLine(“Static Method Called”);
}

public Employee(int empid, string fname, string lname)
{
EmpId = empid;
FirstName = fname;
LastName = lname;
Console.WriteLine(EmpId);
Console.Write(FirstName);
Console.WriteLine(LastName);

}
}
public class Program
{
public static void Main()
{ Employee.static_func();
Employee emp1 = new Employee(10, “Bill”, “Gates”);
}
}

Program 2:-

using System;

struct Employee
{
public int EmpId;
public string FirstName;
public string LastName;

public static void static_func()
{
Console.WriteLine(“Static Method Called”);
}
public Employee() //Throws_Error
{
FirstName = “no first name”;
LastName = “no last name”;

Console.WriteLine(“First name:”,FirstName);

Console.WriteLine(“Last name:”,LastName);

}

}
public class Program
{
public static void Main()
{ Employee.static_func();
Employee emp1 = new Employee();

}
}

The above program 1 contains static function and also a constructor with three parameters. Constructor : Name of the function used inside the structure/class will contain same name of the structure/class name.There are two types of fuctions used inside structure/class¬† know as static functions and non static functions. For calling a static function from main function the¬† is no need of object creation. Alternatively for calling a non static function from main function , object must be created to use that function. Static function inside C# structure is created with the static keyword. But you cannot create explicit parameterless constructor in C# structures. It will throw an error “Structs cannot contain explicit parameterless constructors.“( For example check Program 2).Declaring explicit parameterised constructors is possible in C# structures.

Srihari Lakshminarasimhan

Leave a Reply

Your email address will not be published. Required fields are marked *