Hello, friends in this tutorial I am going to explain you about Classes and Objects in C#.

Introduction to Classes and Objects:

Classes and Objects are very important topics of Object Oriented Programming. After completing this tutorial you will be able to understand the following topics:

  • Classes in C#.
  • Objects in C#.
  • How to create an object of a class in C#.
  • How to call members of a class.

Class:

A class is a blueprint for an object that encapsulates data and behaviour of a type. The class enables us to create our own custom types by simply grouping events, methods and variable. Classes can be act as templates for other classes in form of inheritance.

Declaring Classes:

A Class can be declared using the class keyword, as shown in the below example:

public class MyClass

{

// Your Data Goes here

}

As you can see in the above example class is preceded by public access modifier. Access modifiers describe who can create an object of this class and who can access this class. We will learn more on Access modifiers in later sessions. After class keyword, we define the name of the class. Inside curly braces, we define properties, methods and events.

As we are already familiar with the fact that classes encapsulate data and method inside itself. Let’s elaborate this fact with few terms related to C#.

  • The Property describes the data that we want to encapsulate inside the class.
  • The Method describes the operation that we want to perform on that data.

To get a better understanding about classes and object let’s move towards real word and understand each term with an example.

Suppose there is a class named Employee. So which type of data the Employee class can hold? EmployeeID, EmploeeName, Address. So the Employee class has the following Properties.

EmployeeID: EmployeeID will be used to store unique number that would represent the Employee.

EmployeeName: This will be used to store Name of the Employee as a String.

EmployeeAddress: This will be used to store Address of the Employee as a String.

Now we know that what data the Employee class will be held. Now we need to come to the second point, what operation we will perform on this data. Our Employee class can have two methods to perform an operation on the data.

SetEmployeeDetails(): This method would be used to set the EmplyeeID, EmployeeName and EmployeeAddress of the Employee.

GetEmployeeDetails(): This method would be used to get the EmployeeID, EmployeeName, EmployeeAddress.

Objects:

An Object in an Object Oriented Programming is a real-time entity. An instance of a class is called the object of that class. We can create as many objects of a class. All objects of a class share the same copy of the member function but maintain a separate copy of properties. We can create an object of a class using “new” keyword. Here is the syntax for creating an object of Employee class.

Employee objEmployee=new Employee();

Note:

  • The “.” operator is used to call member of the class.
  • The “.” Operator links the object name with the member of the class. Suppose Employee class has SetEmployeeDetails method then we can call this method like this.
           objEmloyee. SetEmployeeDetails(param1,param2…).

 

Classes and Objects

Where objEmployee is the name of the object of Employee class. The keyword “new” is responsible for creating an object of Employee class.

Let’s start creating an application for understanding more about Class and Object in C#.

1- Open visual studio and create a console application with the name ClassAndObjectDemo.

Classes and Objects

2-  Create a class with the name Employee.

Classes and Objects

 

Step 3- Declare three variables in Employee Class like this:

       int _iEmployeeID;

       string _sEmployeeName;

       string _sEmployeeAddress;

These variables will store data like EmployeeID, EmployeeName, EmployeeAddress in Employee Class.

Step 4- Now First thing what we need to do is to store data related to Employee into these variables. For achieving this task we need to create a method that will store data into these variables. Here is the method for storing Employee Data:

  public void SetEmployeeDetails(int iEmployeeID,string sEmployeeName,string sEmployeeAddress)

        {




            _iEmployeeID = iEmployeeID;

            _sEmployeeName = sEmployeeName;

            _sEmployeeAddress = sEmployeeAddress;




        }

The SetEmployeeDetails method accepts three parameter iEmployeeID, sEmployeeName, sEmployeeAddress.

Step 5 – Second thing what we need to achieve is to access data stored in these variables. Here is the method for retrieving Employee Data.

  public void GetEmployeeDetails()

        {

            Console.WriteLine("Employee ID {0}", _iEmployeeID);

            Console.WriteLine("Employee Name {0}", _iEmployeeID);

            Console.WriteLine("Employee Address {0}", _iEmployeeID);

        }

Now our Employee class is ready to execute. That will store and return Employee Data. Here is the complete structure of the Employee Class.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;




namespace ClassAndObjectDemo

{

   public class Employee

    {

       int _iEmployeeID;

       string _sEmployeeName;

       string _sEmployeeAddress;

        

        public void SetEmployeeDetails(int iEmployeeID,string sEmployeeName,string sEmployeeAddress)

        {




            _iEmployeeID = iEmployeeID;

            _sEmployeeName = sEmployeeName;

            _sEmployeeAddress = sEmployeeAddress;




        }

        public void GetEmployeeDetails()

        {

            Console.WriteLine("Employee ID {0}", _iEmployeeID);

            Console.WriteLine("Employee Name {0}", _iEmployeeID);

            Console.WriteLine("Employee Address {0}", _iEmployeeID);

        }

       

    }

}

Step 6- Now we need to create an object of the Employee class. Now the question is why we need to create an object of Employee class? Is it not possible to access the members of the Employee class directly? The answer is no. Because we did not mark the Employee class as static. A static class can contain only static members inside the class. We will learn more on static class and static members in later tutorials. Go to Program.cs file and create an object of the Employee class and call the members of the Employee class. Here is the code for Program.cs file.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;




namespace ClassAndObjectDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            Employee objEmployee = new Employee();

            objEmployee.SetEmployeeDetails(1,"Vinod Palne","vinodpalne@gmail.com");

            objEmployee.GetEmployeeDetails();

            Console.ReadKey();

         }

    }

}

Run the application and see the output.

Classes and Objects

You can see the Employee Data as an output in console window.

Thank you for spending your precious time. Hope this post about Classes and Objects in C# is useful for you. We will continue on useful topics in later sessions.

125 Comments

  • Hmm it appears like your website ate my first comment (it was super long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog blogger but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d really appreciate it.

  • Thanks , I’ve recently been looking for info approximately this topic for a while and yours is the best I have discovered till now. But, what in regards to the conclusion? Are you positive about the supply?|

  • Nice post. I learn something totally new and challenging on blogs I stumbleupon on a daily basis. It will always be helpful to read articles from other authors and practice something from their sites. |

  • Very nice post. I just stumbled upon your weblog and wanted to say that I’ve truly enjoyed surfing around your blog posts. After all I will be subscribing to your feed and I hope you write again very soon!

  • I have been exploring for a bit for any high quality articles or blog posts on this sort of area . Exploring in Yahoo I at last stumbled upon this site. Reading this information So i am happy to convey that I have a very good uncanny feeling I discovered exactly what I needed. I most certainly will make certain to don’t forget this site and give it a look on a constant basis.

  • Yesterday, while I was at work, my cousin stole my iphone and tested to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My iPad is now broken and she has 83 views. I know this is entirely off topic but I had to share it with someone!

  • Can I just say what a reduction to search out somebody who truly is aware of what theyre speaking about on the internet. You definitely know the right way to bring a difficulty to light and make it important. More individuals have to learn this and understand this side of the story. I cant consider youre not more in style because you positively have the gift.

  • Thanks so much for providing individuals with an extraordinarily superb chance to check tips from this web site. It can be very pleasurable and packed with a lot of fun for me personally and my office peers to search your website the equivalent of thrice in a week to find out the newest stuff you have got. Not to mention, I’m also usually astounded with all the powerful points served by you. Some 3 ideas in this posting are really the most beneficial I’ve had.

  • It’s actually a cool and helpful piece of information. I am glad that you shared this helpful info with us. Please keep us up to date like this. Thanks for sharing.

  • Thanks for your write-up on this website. From my own experience, many times softening upward a photograph may well provide the photography with an amount of an inspired flare. Oftentimes however, the soft cloud isn’t just what exactly you had in mind and can quite often spoil an otherwise good photo, especially if you thinking about enlarging that.

  • Hi there everyone, it’s my first pay a quick visit at this web site, and post is genuinely fruitful for me, keep up posting these content.|

  • What’s Happening i am new to this, I stumbled upon this I’ve found It positively useful and it has helped me out loads. I hope to contribute & aid other users like its aided me. Good job.

  • This article gives clear idea in favor of the new people of blogging, that truly how to do blogging and site-building.|

  • medicaments contre l’anxiete therapies breves pdf [url=https://www.open.edu/openlearn/profiles/zv916875#]Gabapentine kaufen online ohne rezept[/url] therapie de couple toulouse pharmacie mejanes aix en provence . pharmacie quizac brest, pharmacie lafayette nice pharmacie en ligne ile de france therapie magnetique , pharmacie de garde aujourd’hui dijon pharmacie beaulieu harfleur . antimalarial therapy pharmacie de garde marseille plan de campagne [url=https://www.open.edu/openlearn/profiles/zv916768#]Modafinil kaufen online apotheke deutschland[/url] medicaments infection urinaire traitement paludisme . pharmacie galerie auchan illkirch pharmacie lafayette eysines pharmacie monge aix en provence pharmacie de garde kochersberg https://www.open.edu/openlearn/profiles/zv917011# therapie cognitivo comportementale tdah pharmacie aix en provence jas de bouffan , pharmacie lafayette muret. pharmacie beaulieu medicaments keppra [url=http://tdedchangair.com/webboard/viewtopic.php?f=2&t=44878]Brest therapie comportementale et cognitive orne u[/url] a14ff0b , medicaments fer.

  • pharmacie tours pharmacie gare avignon [url=https://www.open.edu/openlearn/profiles/zv917528#]kaufen Zithromax[/url] therapies cognitivo-comportementales efficacite pharmacie de garde marseille 11eme . pharmacie de garde aujourd’hui juan les pins, therapie comportementale et cognitive geneve pharmacie place wilson brest generique du spasfon comprime , pharmacie brest pas cher pharmacie du centre . act therapy overview therapie comportementale et cognitive saint nazaire [url=https://www.open.edu/openlearn/profiles/zv917779#]Singulair 10 mg rezeptfrei kaufen apotheke[/url] medicaments nephrotoxiques pharmacie auchan v2 . therapies york pharmacie garde autour de moi therapie de couple namur pharmacie Г  proximiteпїј https://www.open.edu/openlearn/profiles/zv917011# pharmacie leclerc plerin pharmacie verte colline aix en provence doxycycline en ligne [url=https://www.open.edu/openlearn/profiles/zv908516#]doxycycline 100 mg prix[/url], therapie cognitivo-comportementale montreal. pharmacie de garde marseille joliette traitement reflux gastrique [url=https://forumannou.cirad.fr/viewtopic.php?f=8&t=36540&p=2077693#p2077693]Stuff sur produits medicamenteux is[/url] f0bc777 , therapie de couple fribourg.

  • pharmacie de garde marseille 6 octobre, act therapy uk training act therapy negative thoughts [url=https://bitly.com/3ra8lSh+#]Acheter Seroquel en Suisse[/url] , https://bit.ly/3c9FKIG# pharmacie bordeaux ginko. pharmacie fontenaille aix en provence [url=https://bitly.com/316bwA1+#]Bupropion 150 mg sans ordonnance[/url] , therapies innovantes definition pharmacie brest , therapies psychocorporelles. pharmacie de garde cherbourg pharmacie test covid , pharmacie avenue jean dalmas aix en provence pharmacie auchan avignon [url=https://corpsnews.com/2020/03/16/sigap-prajurit-wijayakusuma-cek-kesehatan/#comment-1394980]community colleges near me with dorms de[/url] f02205e , therapies comportementales et cognitives pleine conscience. pharmacie orthopedie aix en provence keto parapharmacie leclerc , pharmacie vourch brest pharmacie lafayette pamiers pharmacie aeroport bordeaux merignac. pharmacie polygone pharmacie bailly montbrison traitement therapies breves.

  • pharmacien hopital bourges, medicaments yeux secs pharmacie bailly yvelines [url=https://bitly.com/3tMoi2R+#]Acheter Cytotec en Suisse[/url] , https://bitly.com/317iLYa+# pharmacie ouverte dimanche. pharmacie veterinaire avignon [url=https://bit.ly/3f6GSPa#]Doxycycline 200 mg sans ordonnance[/url] , therapie cognitivo comportementale toulouse pharmacie lafayette perpignan , pharmacie ouverte dimanche marseille. pharmacie lafayette le puy pharmacie amiens sud , therapie cognitivo comportementale yonne pharmacie ouverte brest [url=https://www.successdigestforum.com/viewtopic.php?f=10&t=1530860]climax community biology definition a level de[/url] ff0bc77 , traitement avc. pharmacie morvan brest therapie cognitivo-comportementale quebec , therapie de couple islam pharmacie aeroport paris beauvais pharmacie en ligne ordonnance. act therapy online resources pharmacie clos des fontaines avignon pharmacie giphar angers.

  • therapies have had considerable success traitement herpes genital , pharmacie de garde aujourd’hui houilles pharmacie jules verne amiens , https://www.bing.com/news/apiclick.aspx?ref=FexRss&aid=&url=https://u.to/yfYtGw# pharmacie lafayette strasbourg pharmacie franconville pharmacie annecy vieille ville [url=https://www.etracker.com/lnkcnt.php?et=qPKGYV&url=https://bitly.com/3lLrwkg+#]Clopidogrel 75 mg preis[/url] , pharmacie bourges carrefour pharmacie auchan nogent , [url=https://forum.cryptarch.wiki/viewtopic.php?f=4&t=596948]pharmacie leclerc saint quentin Eu am[/url] 14ff0bc pharmacie leclerc istres telephone. pharmacie hospitaliere bourges therapie cognitivo-comportementale ordre des psychologues [url=https://www.bing.com/news/apiclick.aspx?ref=FexRss&aid=&url=https://bitly.com/3w3oih1+#]Azithromycine 1000 mg livraison rapide[/url] , pharmacie universite avignon pharmacie de garde marseille dimanche , pharmacie quetigny. pharmacie de garde aujourd’hui saint maur des fosses, pharmacie boulogne billancourt dimanche ysomega pharmacie en ligne . pharmacie metz, medicaments migraine pharmacie ouverte woippy pharmacie leclerc montbeliard pharmacie menard avignon .

  • pharmacie angers ouverte dimanche pharmacie ouverte niort Viagra mejor precio [url=https://www.bing.com/news/apiclick.aspx?ref=FexRss&aid=&url=http://viagragenerico.uno/#]Viagra Generico 50 mg[/url] , pharmacie angers ouverte dimanche. pharmacie simeon beauvais pharmacie auchan kb therapie de couple separation , pharmacie albigny annecy le vieux. pharmacie carrefour beaulieu nantes pharmacie moderne amiens traitement invisalign prix [url=https://forumannou.cirad.fr/viewtopic.php?f=8&t=45226&p=2115182#p2115182]positive reinforcement kittens ohio pharmacie toulon suisse generico[/url] a14ff0b , pharmacie de garde aujourd’hui 77 traitement joint de dilatation .

  • pharmacie brest super u pharmacie pre bourges comprar Viagra Generico [url=https://www.bing.com/news/apiclick.aspx?ref=FexRss&aid=&url=http://viagragenerico.uno/#]comprar Viagra[/url] , pharmacie de garde paris 16. act therapy for ptsd pharmacie de garde aujourd’hui saint maur des fosses traitement johnson , pharmacie des prГЄcheurs – totum pharmaciens aix-en-provence. pharmacie saint priest pharmacie rouen pharmacie amiens delpech [url=http://superwesele.pl/czy-nie-za-wczesnie/the-new-england-patriots-are-in-their-eighth-consecutive-conference/new/#new]positive affirmations in the morning Au therapy couples interventions spain generico[/url] 70a2ff0 , pharmacie brunet bourges pharmacie ouverte dimanche .

  • 489828 63642Thank you for the auspicious writeup. It in truth used to be a amusement account it. Glance complex to much more added agreeable from you! Nevertheless, how could we be in contact? 458364

  • environments classroom labels positive words encouragement , followers javelin. community action smithfield nc community action partnership new york . friends monopoly https://www.gamereactor.pt/blog/#, community action mobile al positive correlation in statistics positive and negative number rules [url=https://skihighcannabis.com/2020/03/millennials/#comment-1989401]positive adjectives to describe a person EuropeEspana[/url] 206a2_2 , positive affirmations to send to friends autocad software free download full [url=http://buyautocad.design/#]Buy AutoCAD online[/url] , community college las vegas community acquired pneumonia questions planning permission process uk .

  • I do agree with all the ideas you have presented in your post. They’re really convincing and will certainly work. Still, the posts are too short for newbies. Could you please extend them a little from next time? Thanks for the post.

  • I feel that is among the so much vital information for me. And i am glad studying your article. But wanna observation on few normal things, The site style is wonderful, the articles is in point of fact great : D. Good job, cheers

  • pharmacie en ligne rouen formation therapie act toulouse , pharmacie aix en provence de garde pharmacie auchan st quentin , https://www.etracker.com/lnkcnt.php?et=qPKGYV&url=https://is.gd/WHMZZz# pharmacie bourges nord pharmacie ouverte bordeaux centre pharmacie angers boulevard saint michel [url=https://www.bing.com/news/apiclick.aspx?ref=FexRss&aid=&url=https://bitly.com/3a42jx2+#]ivermectine acheter[/url] , ufr pharmacie amiens these pharmacie lafayette metz , [url=http://rnr-rkc.com.ua/categories/Fam_Apost_2018/19#comment-1411060]pharmacie de garde aujourd’hui montpellier fresnes[/url] 770a2ff pharmacie de garde aujourd’hui dimanche. pharmacie a proximite orleans pharmacie vauthier argenteuil [url=http://channel.pixnet.net/newdirect.php?blog=cr19h3id&serial=0&url=https://bitly.com/3sblb3m+#]acheter ivermectine 12 mg[/url] , pharmacie illkirch traitement otite , pharmacie place aristide briand argenteuil. therapies skin, act therapy nhs pharmacie de garde aujourd’hui noyon . depression therapies alternatives, pharmacie ouverte uzemain pharmacie boulogne billancourt rue du point du jour pharmacie bailly paris horaires pharmacie argenteuil rue paul vaillant couturier .

  • medicaments yam pharmacie psg argenteuil , pharmacie intermarche amiens pharmacie rennes , https://www.etracker.com/lnkcnt.php?et=qPKGYV&url=https://bitly.com/3wZD74H+# pharmacie avignon horaire pharmacie de garde marseille quartier nord pharmacie lerouge boulogne billancourt [url=https://www.etracker.com/lnkcnt.php?et=qPKGYV&url=https://u.to/9ZQ9Gw]Ivermectine en pharmacie[/url] , medicaments et alcool therapies cognitivo-comportementales , [url=https://wildtroutstreams.com/ohio-brookies/#comment-342051]pharmacie brest liberte europe[/url] 06a8_7e therapie cognitivo comportementale douleur chronique. pharmacie pont saint jean beaulieu pharmacie huyghe amiens [url=https://www.etracker.com/lnkcnt.php?et=qPKGYV&url=https://bit.ly/3wRnaxm#]generique Stromectol[/url] , progressive therapy alternatives inc pharmacie de garde marseille janvier 2020 , therapies hypnotiques (patrick hygonnet). pharmacie annecy le vieux albigny, medicaments xanax therapies psychomotrices et recherches . therapie de couple outaouais, therapies comportementales et cognitives marseille traitement bouton de fievre therapie quantique avis therapies alternatives signification .

  • community action partnership lewiston idaho individual level covid data , Sale Ivermectin 3 mg [url=http://ivermectinsale.me/#ivermectin-pills-for-sale]Ivermectin covid[/url] positive feedback mechanism examples. positive z score table positive pregnancy test after miscarriage . planning process has, community action xenia ohio cultural relativism community health center volunteer [url=https://es.3dot1.com/nuevos-enfoques-organizacionales-y-liderazgo-2/comment-page-38181/#comment-647415]culture in spanish Japan[/url] f0bc777 , community action greenfield ma , positive quotes short .

  • individual level theories of juvenile delinquency positive pregnancy test second line faint , Ivermectin medication [url=http://ivermectinsale.me/#ivermectin-for-sale]ivermectin otc[/url] community care first aid vancouver. positive minus negative community bible church website . synonym community quality, positive correlation examples in real life popular community bank near me positive words letter r [url=http://www.hikmatleaders.org/content/what-does-day-hikmatleaders-look?page=6748#comment-664744]positive words values nd[/url] f0bc777 , positive words letter s , community america raytown .

  • 750723 580176I enjoyed reading your pleasant web site. I see you offer priceless info. stumbled into this web site by chance but Im certain glad I clicked on that link. You undoubtedly answered all the questions Ive been dying to answer for some time now. Will undoubtedly come back for a lot more of this. 1360

  • You’ve made some really good points there. I checked on the internet for more information about the issue and found most people will go along with your views on this site.|

  • Hi! Would you mind if I share your blog with my myspace group? There’s a lot of people that I think would really appreciate your content. Please let me know. Thanks|