Sep 20, 2011

Array of struct in C#

using System;

namespace arrayDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Student[] arr = new Student[3];
            arr[0] = new Student("Tom", 10, 50.0f);
            arr[1] = new Student("Jerry", 20, 80.5f);
            arr[2] = new Student("Davis", 30, 70.0f);

            //printing values of each elements in the array
            foreach (Student element in arr)
            {
                element.display();
            }
            Console.ReadKey();
        }
    }
}

struct Student
{
    string name;
    int roll;
    float marks;

    public Student(string name, int roll, float marks)
    {
        this.name = name;
        this.roll = roll;
        this.marks = marks;
    }
    public void display()
    {
        Console.WriteLine("{0} {1} {2}", roll, name, marks);
    }
}

10 Tom 50
20 Jerry 80.5
30 Davis 70

using System;

namespace arrayDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Student[] arr = {new Student("Tom", 10, 50.0f),
                             new Student("Jerry", 20, 80.5f),
                             new Student("Davis", 30, 70.0f)};

            //printing values of each elements in the array
            foreach (Student element in arr)
            {
                element.display();
            }
            Console.ReadKey();
        }
    }
}

struct Student
{
    string name;
    int roll;
    float marks;

    public Student(string name, int roll, float marks)
    {
        this.name = name;
        this.roll = roll;
        this.marks = marks;
    }
    public void display()
    {
        Console.WriteLine("{0} {1} {2}", roll, name, marks);
    }
}

No comments:

Post a Comment