C# - Properties in Interface Example

In this example, we will learn about the properties in the interface using C# program?
Submitted by Nidhi, on November 05, 2020 [Last updated : March 22, 2023]

Here, we create an interface with properties then we will implement the properties in the Student class.

C# program to demonstrate the example of properties in the interface

The source code to demonstrate the properties in the interface is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# - Properties in Interface Example.

using System;

interface Inf
{
    int ID { get; set; }
    string Name { get; set; }
}

class Student : Inf
{
    string _name;

    public int ID
    {
        get;
        set;
    }

    public string Name
    {
        get { return this._name; }
        set { this._name = value.ToUpper(); }
    }
}

class Program
{
    static void Main()
    {
        Inf inf = new Student();

        inf.ID = 101;
        inf.Name = "Rohit Sharma";

        Console.WriteLine(inf.ID);
        Console.WriteLine(inf.Name);
    }
}

Output

101
ROHIT SHARMA
Press any key to continue . . .

Explanation

In the above program, we created an interface Inf that contains properties ID and Name then we implemented interface properties in the Student class.

Now look to the Program class, the Program class contains the Main() method, The Main() method is the entry point for the program. Here we created the object of Student class and initialized the inf reference.

inf.ID = 101;
inf.Name = "Rohit Sharma";

Here, we set the properties ID and Name.

Console.WriteLine(inf.ID);
Console.WriteLine(inf.Name);

In the above code, we get values using Get property and print them on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.