Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access functions inside struct in C#

Tags:

c#

class Program
{ 
   public  struct course
   {
        public string name;
        public int elecode;
        public int credit;


        public static void getdetails()
        {
            Console.WriteLine("Enter your Name");
           Ele.name = Console.ReadLine();

        }
   }

    static void Main(string[] args)
    {

        course ele;
        ele.getdetails();

    }
}
like image 937
zoho_deployment Avatar asked Feb 03 '16 06:02

zoho_deployment


People also ask

Can we use function inside structure in C?

Member functions inside the structure: Structures in C cannot have member functions inside a structure but Structures in C++ can have member functions along with data members.

Can you define functions inside struct?

No, you can't. Structs can only contain variables inside, storing function pointers inside the struct can give you the desired result. Save this answer.

How do you access items in a struct?

Accessing data fields in structs Although you can only initialize in the aggregrate, you can later assign values to any data fields using the dot (.) notation. To access any data field, place the name of the struct variable, then a dot (.), and then the name of the data field.

Can you store a function in a struct?

Function pointers can be stored in variables, structs, unions, and arrays and passed to and from functions just like any other pointer type. They can also be called: a variable of type function pointer can be used in place of a function name.


1 Answers

  1. Your method getdetails should not be static
  2. Remove Ele. inside getdetails
  3. Initialize course ele variable

Your code:

class Program
{ 
   public  struct course
   {
        public string name;
        public void getdetails()
        {
            Console.WriteLine("Enter your Name");
            name = Console.ReadLine();
        }
   }

    static void Main(string[] args)
    {    
        course ele = new course();
        ele.getdetails();
    }
}

As was mentioned by @DavidHeffernan in comment about poor design, you have to know where to use class instead of struct to escape problems, when a value type gives you a COPY of the value

like image 160
Michael Avatar answered Sep 27 '22 22:09

Michael