Structs
are just like classes.
Structs
can have
a.
Private
and public properties
b.
Constructors
c.
Methods
etc.,
There
are differences between structs and classes. First let’s see basics of structs.
How to define a
struct?
By
using ‘struct’ keyword, you can define a struct.
Example
struct Employee{ }
Adding constructors
to struct
Just
like how you add constructors to classes, you can add constructors to struct.
struct Employee { private int id; private String firstName; private String lastName; public Employee(int id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } }
Adding methods to
struct
Just
like how a class has methods we can add methods to struct.
struct Employee { private int id; private String firstName; private String lastName; public Employee(int id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } public String getName() { return firstName + "," + lastName; } }
Following is the
complete working application.
Program.cs
using System; struct Employee { private int id; private String firstName; private String lastName; public Employee(int id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } public String getName() { return firstName + "," + lastName; } public int Id { get { return id; } set { id = value; } } public string FirstName { get { return firstName; } set { firstName = value; } } public string LastName { get { return lastName; } set { lastName = value; } } } class Program { static void Main(string[] args) { Employee emp1 = new Employee(1, "Hari Krishna", "Gurram"); Console.WriteLine("Id : {0}", emp1.Id); Console.WriteLine("First Name : {0}", emp1.FirstName); Console.WriteLine("Last Name : {0}", emp1.LastName); } }
Output
Id
: 1
First
Name : Hari Krishna
Last
Name : Gurram
No comments:
Post a Comment