C# Programming for Beginners | C# Code for Creating C# Objects, Calling C# Methods

C# Code for Creating C# Objects, Calling C# Methods


This time we will look at how we can create c# objects, and use those objects to call the methods of the class.  You should have already created the Bird class according to the last part of this series.  If not go back and read that post here: C# Code for declaring C# classes, C# methods and properties.


To create the instance of your class (or object) you need to find the line: static void Main(string[] args)


This is where the program starts its execution.  To create your object you have to state the class name first then give the object a name and then use the “new” keyword like this:


//Create the separate Eagle and Chicken objects


      Bird Eagle = new Bird();


      Bird Chicken = new Bird();




After creating these objects you can refer to them by name.  Here we set the properties of the “Eagle” object:


//Set all the properties of Eagle object


       Eagle.pColour = "Brown";


       Eagle.pHeight = "90cm";


       Eagle.pWeight = "1100grams";


       Eagle.pPredator = true;




To output all the properties to the console window use the WriteLine() method of the Console class like so:


  
//Print all Eagle Properties to the console


   Console.WriteLine("EAGLES PROPERTIES:");


   Console.WriteLine(Eagle.pColour);


   Console.WriteLine(Eagle.pHeight);


   Console.WriteLine(Eagle.pWeight);


   Console.WriteLine("Predator? " + Eagle.pPredator.ToString());


   Eagle.Fly();


   Console.ReadLine();


To call the C# methods of the bird class, use the object name and a dot followed by the method name. 


That’s all it takes to call the method.  I’ve added a ReadLine() call as well – this is just a hack to stop the Console window from closing, so that you can see all the properties and the result of the method call.  I’ll leave you to try and create the Chicken object, using the above as the example.  Test your code using the green debugging arrow in Visual Studio.  The output should be as follows:


EAGLES PROPERTIES:
Brown

90cm
1100grams
Predator? True
Bird is flying




Here is the entire Program.cs class for your reference:

C# Source Code:


using System;


using System.Collections.Generic;


using System.Linq;


using System.Text;






namespace TestClasses


{


  class Program


   {


    public class Bird


    {


        //this is the constructor


        public Bird()


        {


        }


       


        private string colour;


        private string height;


        private string weight;


        private bool predator;


       


        //Properties


        public string pColour


        {


            get{return colour;}


            set{colour = value;}


        }






        public string pHeight


        {


            get { return height; }


            set { height = value; }


        }






        public string pWeight


        {


            get { return weight; }


            set { weight = value; }


        }






        public bool pPredator


        {


            get { return predator; }


            set { predator = value; }


        }






        //Methods - What can the Bird do?


        public void Fly()


        {


            Console.WriteLine("Bird is Flying");


        }






        public void Eat()


        {


            Console.WriteLine("Bird is Eating");


        }






        public void Walk()


        {


            Console.WriteLine("Bird is Walking");


        }


    }






static void Main(string[] args)


        {


         //Create the separate Eagle and Chicken objects


         Bird Eagle = new Bird();


         Bird Chicken = new Bird();






         //Set all the properties of Eagle object


         Eagle.pColour = "Brown";


         Eagle.pHeight = "90cm";


         Eagle.pWeight = "1100grams";


         Eagle.pPredator = true;






         //Set all the properties of Chicken object


         Chicken.pColour = "Yellow";


         Chicken.pHeight = "30cm";


         Chicken.pWeight = "200grams";


         Chicken.pPredator = false;






         //Print all Eagle Properties to the console


        Console.WriteLine("EAGLES PROPERTIES:");


        Console.WriteLine(Eagle.pColour);


        Console.WriteLine(Eagle.pHeight);


        Console.WriteLine(Eagle.pWeight);


        Console.WriteLine("Predator? " + Eagle.pPredator.ToString());






        Eagle.Fly();


  Eagle.Walk();


  Eagle.Eat();






        Console.ReadLine();


        }


    }






}




I hope you have enjoyed this programming tutorial on C# Programming for Absolute Beginners and I hope you have at least learned something about C# objects and C# methods.

C# Programming for Beginners | C# Code for C# classes, methods, properties

If you missed my previous post on C# classes, C# methods and C# objects in code, please read that first (click the link to see that post).  The code that follows is a continuation of that post.


In Visual Studio, create a new console project.  I called mine TestClasses.  A console project runs like the old DOS command line console window. 



Right, so to the code.  Open the Program.cs class and click directly above the “
static void Main(string[] args)” line.  First of all you simply have to declare the class.    


A C# class is declared by using the “public” access modifier and the keyword “class”, followed by the name that you want your class to be, in this case, “Bird”.  If you don’t know what the access modifier is, don’t worry about it for now, just make sure it is public.  The curly brackets show where the beginning and end of the class is, anything in between them is part of the Bird class.

    public class Bird


{


}
So there, you have now declared your C# class.  The class is pretty useless without anything in it, so we’ll have to add a few things.  First of all we need a constructor.  The constructor enables us to create (construct) the objects later on.  Without it we could not create an instance of the class (in this case the Eagle and Chicken objects).
public class Bird


{
       //this is the constructor


        public Bird()


          {


          }



According to our earlier discussion we now need to add the C# methods of the Bird class.  These were Fly() , Eat() and Walk().  Methods are declared almost the same way as classes are.  First the access modifier (“public”) then you need a return type (“void”).  A return type is used if your method needs to return something for later use, here your method returns nothing, therefore here the return type is void.  So add these to your Bird class.
//Methods - What can the Bird do?
   public void Fly()
        {


          //you would put an actions needed here


            Console.WriteLine("Bird is Flying");


        }
        public void Eat()


        {


            Console.WriteLine("Bird is Eating");


        }
        public void Walk()


        {


            Console.WriteLine("Bird is Walking");


        }
So, now we have our class and our class has some methods, which enable it to do something.  The next step is to add the properties of Colour, Height, Weight, Predator.  To do this, first of all declare the variables as follows:
//variables for the properties


        private string colour;


        private string height;


        private string weight;


        private bool predator;
The variables will hold the information.  Notice here that the access modifiers are private.  This means that outside of the class they cannot be accessed.  We are going to set up the access to them so that they can only be accessed through their properties as follows:


The properties either get the contents of the private variable or set the private variable to the value that you will define.  You might have noticed the bool for pPredator.  Why is this bool?  Bool means either true or false, and so here the bird can either be a predator (true), or not (false).


And that is it for setting up your bird class.  Save your project as it is.


Next time here on C# Programming for Absolute Beginners, we’ll take a look at how to use this class to create your Eagle and Chicken objects and also how to use these objects to call the methods from the bird class.  


For more simple programming c# examples please click the link.  This will take you through the C# code for creating C# objects and calling C# methods.

C# Programming for Beginners | C# Classes, C# Methods and C# Objects in Programming

To gain a better understanding of programming concepts such as C# classes, methods, and objects we are going to look at real life things around us that will help us understand the code structure.


What is a C# Class?
A class is a very important part of object oriented techniques.  A class is sometimes described as a “blueprint” which you can use to create an object.  For instance if you had to think of a “Bird” you will probably immediately think of a creature that can fly, with two wings, a beak, two eyes, two feet and covered in feathers.  That is essentially what a class is, an idea of what the object is going to look like.  The class contains properties, for instance: Colour, Height, Weight, Predator.  A class is an abstract idea - it isn’t anything concrete.  To get to something concrete we must use an object.  We’ll look at objects later but first let’s look at methods.


What are C# Methods?
A method is an action that the class can perform.  Looking quickly at the bird class, ask yourself, “How does the bird function, what are the verbs?”  We could say that some methods would be:  Fly() ; Eat() ; Walk().  Therefore these doing words will become the Methods of our class.


What are C# Objects?
An object is an instance of a class.  What would be an instance of our Bird class?  Let’s choose two different objects -Chicken and Eagle to see how they would differ as objects.





Class Bird:
Object Chicken:
Methods:
Fly()
Eat()
Walk()
Properties:
Colour = yellow
Height = 30cm
Weight = 200grams
Predator = no



Class Bird
Eagle
Methods:
Fly()
Eat()
Walk()
Properties:
Colour = brown
Height = 90cm
Weight = 1100grams
Predator = yes


Can you see how the object is different from the class?  They are both of the bird class yet are quite different objects when you look closely at their properties.  The Chicken is much smaller, has a different colour, weighs a different weight and is not a predator.  The Eagle is brown, quite large, heavy and is a predator.  They both however can Fly, Eat, and Walk.
That's it for now, next time on C# Programming for Absolute Beginners, I'll provide the code for the above example using C#.


Here is alink to that post: C# code for classes, methods and properties.


C# Programming for Absolute Beginners - BlogEngine.NET || SubText

I’ve been exploring two open source blog writing engines for .NET


They are:


I really don’t know which one to use, although I am leaning towards BlogEngine.NET.  It is for a website that a feel would do well from the blog-style layout.  It looks like it would be fairly easy to add to and extend.  I think I’ll have to download and fiddle with it a bit.  I’ll post more on my experiences with using it later.


I think that using a blog engine could make web programming a lot easier - giving one the framework, almost like a content management system.

C# Programming for Absolute Beginners | Job Sites

In my previous post about C# beginner programmers' job search I spoke about using online job boards/sites to help you to find that elusive programming job.  

Here are some job sites that I’ve been looking at and have signed up to, to get you started.
Note that there is a bias toward South African sites because this is after all where I live.
Warning:  It won’t take you five minutes (unless you find what you want instantly – not likely).
Before searching make sure you have your CV nearby and be prepared to spend some time browsing and signing up. 


Local: (South Africa)


Pastel Job Site http://www.pnet.co.za/
General.  It’s worth looking through.


Studio29 - http://www.studio29.co.za/
Specialising in IT.


Career Junction - http://www.careerjunction.co.za/
General job board


International:


Monster.com – http://www.monster.com/
Huge general job board.



UK jobs net - http://www.ukjobsnet.co.uk/
Smaller UK based board

It would seem that most computer programming and web programming jobs out there are available online.  This is because (in my opinion) most potential employers expect programmers (quite rightly) to have some sort of access to the internet.

C# Programming for Beginners | Junior Programmer Job Search

Junior programmers have a hard time trying to get started in a career of programming.  There seems to be so many opportunities out there yet they can't seem to gel with what you know or have learnt.


In order to find a job that “fits”, you have to look everywhere.  The thing is, if you’re looking for a job who knows about it?
People will tell you that the best way to get a job, or find out about a vacancy is via word-of-mouth.  Right, so key to that is to let all your friends know that you are on the job hunt, and tell them to keep their ears open for you.  Check.
What else can you do?  Well you’ve probably guessed it already – you have to actively look for jobs.  So how can you do that?  Of course, the old classified section of the newspaper is the perennial starting point.  However, as we all know, the Internet has provided us with a lot of tools to aid us. Enter:  Job Boards. 


You might think that, “I’ll just sign up here, and before you know it I’ll have a fantastic job.”  Right?


Wrong.  There is such a plethora of job boards out there that you’re going to spend a lot of time looking through them to find jobs that are suitable.  Also, not all sites are the same.  Some boards are very generalised, and others are targeted to a specific industry (for example IT).  You are likely to spend a lot of time wending your way through them, trying to sort through all the noise.  After a while you might just start signing up to a few of them, like I did, because “you have to at least do something”.  That’s when you really start with the head scratching,  trying to remember when you worked where, for how long, what did you do for all that time, why etc etc.  Even if you have got a CV with most of the details on it already, you will still be left wondering about some of the fields that they require.


So you’ve signed up now.  “But do they work?” you may ask.  Well, to be honest I’m not sure; I’m still searching for a job after all.  However, two friends of mine (one an electrical engineer, and the other a welder) both got their current job offers through a job site.  This shows that people are using the boards when searching for employees and that yes it must work to some extent.  I must point out here that most “employers” that are looking for employees on these sites are in fact employment agencies.  This doesn’t really change anything (I don’t care if I get a job independently or through an agency, as long as I get a job) but is worth keeping in mind. 


At least uploading a CV to one or two of these boards gets it “out there”.
It is better to have at least the possibility of the right job finding me.  How many calls or emails I get that are relevant, remains to be seen..

C# Programming for Absolute Beginners

Welcome to C# Programming for Absolute Beginners.  This site provides tips and techniques for beginner programmers (or coders) to help with their, sometimes steep, learning curve.  My language is C# .NET and I also work in ASP.NET and sometimes SQL Server.  If you follow C# Programming for Absolute Beginners please comment so that I can answer your questions and others can see learn from them as well.
Thanks.



Technorati Claims Code:
FU5WGDRWE8HK

C# Programming for Beginners - Privacy Policy

This website/blog uses third-party advertising companies to serve ads when visiting this site. These third parties may collect and use information (but not your name, address, email address, or telephone number) about your visits to this and other websites in order to provide advertisements about goods and services of interest to you. If you would like more information about this practice and to know your choices about not having this information used by these companies, you can visit Google's Advertising and Privacy page.

If you wish to opt out of Advertising companies tracking and tailoring advertisements to your surfing patterns you may do so at Network Advertising Initiative.

Google uses the Doubleclick DART cookie to serve ads across it's Adsense network and you can get further information regarding the DART cookie at Doubleclick as well as opt out options at Google's Privacy Center

Privacy

I respect your privacy and I am committed to safeguarding your privacy while online at this site C# Programming for Beginners The following discloses how I gather and disseminate information for this Blog.

RSS Feeds and Email Updates

If a user wishes to subscribe to my RSS Feeds or Email Updates (powered by Feedburner), I ask for contact information such as name and email address. Users may opt-out of these communications at any time. Your personal information will never be sold or given to a third party. (You will never be spammed by me - ever)

Log Files and Stats

Like most blogging platforms I use log files, in this case Statcounter and Sitemeter. This stores information such as internet protocol (IP) addresses, browser type, internet service provider (ISP), referring, exit and visited pages, platform used, date/time stamp, track user’s movement in the whole, and gather broad demographic information for aggregate use. IP addresses etc. are not linked to personally identifiable information.

Cookies

A cookie is a piece of data stored on the user’s computer tied to information about the user. This blog doesn't use cookies. However, some of my business partners use cookies on this site (for example - advertisers). I can't access or control these cookies once the advertisers have set them.

Links

This Blog contains links to other sites. Please be aware that I am not responsible for the privacy practices of these other sites. I suggest my users to be aware of this when they leave this blog and to read the privacy statements of each and every site that collects personally identifiable information. This privacy statement applies solely to information collected by this Blog.

Advertisers

I use outside ad companies to display ads on this blog. These ads may contain cookies and are collected by the advertising companies and I do not have access to this information. I work with the following advertising companies: Google Adsense, ROI Rocket, Project Payday. Please check the advertisers websites for respective privacy policies.