We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 8
/
Learn C#: Classes
In C#, classes are used to create custom types. The
class defines the kinds of information and methods
Included in a custom type.
In C#, whenever an instance of & class is created, its
constructor is called. Like methods, a constructor can
be overloaded. It must have the same name as the
enclosing class. This is useful when you may want to
define an additional constructor that takes @ different
‘number of arguments.
and Objects
system
string name:
int trees
// Here we have the Forest class which
has two pieces of data, called fields.
hey are the "name" and "trees" fields
// Takes two arguments
Forest(int area, string country
‘Area = area
Country = country
// Takes one argument
Forest (int area.
Area
Country
“Unknown”
// Typically, 2 constructor is used to
set initial values and run any code
needed to “set up” an instance
PF looks like a m
J & construc but
od,
its return type and method name
reduced to the name of the enclosing
type.C# Parameterless Constructor
In C#, if no constructors are specified in a class, the
compiler automatically creates a parameteriess
constructor.
public class Freshman
t
public string FirstName
{ get; set; }
public static void Main (string[] args)
{
Freshman £ = new Freshman();
// mame is null
string name = f.FirstName;
// In this example, no constructor is
defined in Freshman, but a parameterless
constructor is still available for use in
Main().C# Access Modifiers
In C#, members of a class can be marked with access
‘modifiers, including p.»\<< and svivase «A pubic
member can be accessed by other classes. A. o-iv
member can only be accessed by code in the same
class.
By default, elds, properties, and methods are private,
and classes are public.
public class Speech
t
private string greeting
reeting:
private string FormalGreeting()
t
return $"{greeting} and salutations";
public string Scream()
t
return FormalGreeting() .ToUpper() ;
}
public static void Main (string[] args)
t
Speech s = new Speech();
//string sfg = s.FormalGreeting(); //
Error!
//string sg = s.greeting; // Error!
Console.WriteLine(s.Scream()) 5
// In this example, greeting and
FormalGreeting() are private. They cannot
be called from the Main() method, which
belongs to a different class. However the
code within Scream() can access those
members because Scream() is part of the
same class.C# Field
In C#, a field stores a piece of data within an object. It
acts like a variable and may have a different value for
leach instance of a type.
{field can have a number of modifiers, including:
ublke , peivete , static pan reaconty .Hfme access
modifier is provided, a field is. o-va\e by default.
public class Person
{
private string FirstName;
private string lastNam
// In this example, firstNane and
lastName are private fields of the Person
class.
// For effective encapsulation, a field
is typically set to private, then
accessed using a property. This ensures
that values passed to an instance are
validated (assuming the property
implements some kind of validation for
its field).C# this Keyword
InC#, the crs keyword refers to the current instance
of a class.
// We can use the this keyword to refer
to the current class’s members hidden by
similar names:
public NationalPark(int area, string
state)
{
this.area = area;
this.state = state;
// The code below requires duplicate
code, which can lead to extra work and
errors when changes are needed:
public NationalPark(int area, string
state)
{
area = area;
state = state;
}
public Nationalpark(int area)
t
state = "Unknown";
}
// Use this to have one constructor call
another:
public NationalPark(int area) : this
(state, "Unknown"
t}C# Members
In C#, a class contains members, which define the kind
of data stored in a class and the behaviors a class can
perform,
C# Dot Notation
In C#, a member of a class can be accessed with dot
notation,
C# Class Instance
In C#, en object is an instance of a class. An object can
be created from a class using the =» keyword,
class Forest
t
public string name;
public string Name
{
get { return name; }
set { name = value; }
// A member of a class can be a field
(like name), a property (like Name) or
a method (like get()/set()). It can also
be any of the following
// Constants
JI Constructors
// Events
// Finalizers
// Indexers
// Operators
// Nested Types
string greeting = “hello”
J] Prints 5
Console.WriteLine(greeting. Length) ;
J/ Returns 8
Math.Min(B, 920);
Burger cheeseburger = new Burger();
// If a class is a recipe, then an object
is a single meal made from that recipe.
House tudor = new House();
// Tf a class is a blueprint, then an
object is a house made from that
blueprint.C# Property
In C#, a property is a member of an object that
controls how one field may be accessed and/or
modified. A property defines two methods: a
‘method that describes how a field can be accessed,
and a -<:() method that describes how a feld can be
modified.
(One use case for properties is to control access to a
field. Another isto validate values for a fel.
C# Auto-Implemented Property
In C#, an auto-implemented property reads and writes
to.a private field, like other properties, but it does not.
require explicit definitions for the accessor methods
nor the field Itis used with the ss: syntax,
This helps your code become more concise.
public class Freshman
private string firstName;
public string FirstName
get { return firstName;
set { firstName - value; }
public static void Main (string[] args)
Freshman f = new Freshman();
ouie";
f.FirstName =
// Prints “Louie’
Console.WriteLine(f. FirstName) ;
// In this example, FirstNane is
a property
public class HotSauce
public string Title
{ get; set }
public string Origin
{ get; set; }
// In this example, Title and Origin are
auto-implemented properties. Notice that
a definition for each field (like private
string title) is no longer necessary.
A hidden, private field is created for
each property during runtime.C# Static Constructor
In C#, a static constructors run once per type, not per
Instance. It must be parameterless. tis invoked before
the type is instantiated or a static member is accessed.
C# Static Class
In CH, a static class cannot be instantiated. Its
‘members are accessed by the class name.
This is useful when you want a class that provides a set,
of tools, but doesn't need to maintain any internal data,
vow) fs acommonly-used static class.
class Forest
static Forest()
(
Console. writeLine(”
Initialized");
ype
// In this class, either of the following
two lines would trigger the static
constructor (but it would not be
triggered twice if these two lines
followed each other in succession):
Forest f = new Forest();
Forest .Define();
//Two examples of static classes calling
static methods:
Math.Min(23, 97);
Console.WriteLine("Let's Go!");