w3resource
C# Sharp Programming Exercises

C# Sharp Exercises: Struct declare using default and parameterized constructors

C# Sharp STRUCTURE : Exercise-7 with Solution

Write a program in C# Sharp to demonstrates struct initialization using both default and parameterized constructors.

Sample Solution:-

C# Sharp Code:

using System;
public struct newStruct
{
    public int m, n;
    public newStruct(int pt1, int pt2)
    {
        m = pt1;
        n = pt2;
    }
}
// Declare and initialize struct objects.
class strucExer7
{
    static void Main()
    {
		Console.Write("\n\nStruct declares using default and parameterized constructors :\n");
		Console.Write("-----------------------------------------------------------------\n");
        newStruct myPoint1 = new newStruct();
        newStruct myPoint2 = new newStruct(25, 25);


        Console.Write("\nnewStruct 1: ");
        Console.WriteLine("m = {0}, n = {1}", myPoint1.m, myPoint1.n);

        Console.Write("newStruct 2: ");
        Console.WriteLine("m = {0}, n = {1}", myPoint2.m, myPoint2.n);

        Console.WriteLine("\nPress any key to exit.");
        Console.ReadKey();
    }
}

Sample Output:

Struct declares using default and parameterized constructors :                                                
-----------------------------------------------------------------                                                
newStruct 1: m = 0, n = 0                                                                                     
newStruct 2: m = 25, n = 25                                                                                        
Press any key to exit.

Flowchart:

Flowchart: Struct declare using default and parameterized constructors

C# Sharp Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C# Sharp to declares a struct with a property, a method, and a private field.
Next: Write a program in C# Sharp to demonstrates struct initialization without using the new operator.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming