C# - SPLessons

C# Classes and Methods

Home > Lesson > Chapter 8
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

C# Classes and Methods

C# Classes and Methods

Class

shape Description

Class is the basic building block of object oriented programming. It is a blueprint or template which consists of methods and variable. Class encapsulates variable members, functions, structure, properties and many more components.

shape Program Description

shape Syntax

Class Example { }

shape Example

In the below example you can see the basic example. [csharp] using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SPLessons { class Program { static void Main(string[] args) { Console.WriteLine("Hello"); } } } [/csharp] Output:

Methods

shape Description

Methods are block of code which helps to perform a given task .Using methods logic and group related code can be separated.It takes parameters as input and returns a value which is the result ,though this property is optional.

shape Syntax

1. Without Parameter attribute modifier return-type method-name() { } 2. With Parameter attribute modifier return-type method-name(parameters) { }

shape Example

In the below example you can see the basic example. [csharp] using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SPLessons { class Program { static void Main(string[] args) { string myChoice; OneMethod om = new OneMethod(); do { myChoice = om.getChoice(); //Display user choice switch (myChoice) { case "C": case "c": Console.WriteLine("Play Cricket"); break; case "F": case "f": Console.WriteLine("Play FootBall."); break; default: Console.WriteLine("{0} Invalid choice", myChoice); break; } // Pause to allow the user to see the results Console.WriteLine(); Console.Write("press Any key to continue..."); Console.ReadLine(); } while (myChoice != "Q" && myChoice != "q"); } class OneMethod { public string getChoice() { string myChoice; // Print A Menu Console.WriteLine("Sports Corner\n"); Console.WriteLine("C - Cricket"); Console.WriteLine("F - Football"); Console.WriteLine("Q - Quit\n"); Console.Write("Choice (C,F,or Q): "); // Retrieve the user's choice myChoice = Console.ReadLine(); Console.WriteLine(); return myChoice; } } } } [/csharp] Output: