w3resource
C# Sharp Programming Exercises

C# Sharp Exercises: Declares a struct with a property, a method, and a private field

C# Sharp STRUCTURE: Exercise-6 with Solution

Write a program in C# Sharp to declares a struct with a property, a method, and a private field.

Sample Solution:-

C# Sharp Code:

using System;
struct newStruct
{
    private int num;

    public int n
    {
        get 
        {
            return num;
        }
        set 
        {
            if (value < 50)
                num = value;
        }
    }
    public void clsMethod()
    {
        Console.WriteLine("\nThe stored value is: {0}\n", num);
    }
}
class strucExer6
{
    public static void Main()
    {
		Console.Write("\n\nDeclares a struct with a property, a method, and a private field :\n");
		Console.Write("----------------------------------------------------------------------\n");	
        newStruct myInstance = new newStruct();
        myInstance.n = 15;
        myInstance.clsMethod();
    }
}

Sample Output:

Declares a struct with a property, a method, and a private field :                                            
----------------------------------------------------------------------                                           
The stored value is: 15

Flowchart:

Flowchart: Declares a struct with a property, a method, and a private field

C# Sharp Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C# Sharp to show what happen when a struct and a class instance is passed to a method.
Next: Write a program in C# Sharp to demonstrates struct initialization using both default and parameterized constructors.

What is the difficulty level of this exercise?



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