w3resource

C#: 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 that declares a struct with a property, a method, and a private field.

Sample Solution:-

C# Sharp Code:

using System;

// Declaration of a structure named newStruct
struct newStruct
{
    private int num; // Private field 'num' in the structure

    // Public property 'n' with getter and setter
    public int n
    {
        // Getter returns the value of 'num'
        get
        {
            return num;
        }
        // Setter assigns value to 'num' if it is less than 50
        set
        {
            if (value < 50)
                num = value;
        }
    }

    // Method to display the value stored in 'num'
    public void clsMethod()
    {
        Console.WriteLine("\nThe stored value is: {0}\n", num);
    }
}

// Main class
class strucExer6
{
    // Main method
    public static void Main()
    {
        // Displaying a message indicating the structure's components
        Console.Write("\n\nDeclares a structure with a property, a method, and a private field :\n");
        Console.Write("----------------------------------------------------------------------\n");

        // Creating an instance of newStruct
        newStruct myInstance = new newStruct();

        // Assigning a value using the property 'n'
        myInstance.n = 15;

        // Calling the method 'clsMethod' to display the stored value
        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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/csharp-exercises/structure/csharp-structure-exercise-6.php