Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C# Sharp Exercises: Declares a structure 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 structure 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 structure 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 structure 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?

Test your Programming skills with w3resource's quiz.