0% found this document useful (0 votes)
11 views

Access Static Overload

The document discusses classes in C#, including access modifiers, static members, overloaded methods, instantiation, object initialization, and reference types. It provides examples of defining properties, fields, methods, constructors, and static members.

Uploaded by

SBnet Silva
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Access Static Overload

The document discusses classes in C#, including access modifiers, static members, overloaded methods, instantiation, object initialization, and reference types. It provides examples of defining properties, fields, methods, constructors, and static members.

Uploaded by

SBnet Silva
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Chapter 12

Classes:
Access Modifiers
Static Members
Overloaded Methods

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 1
Instantiation – State – Initializers – Reference Type
✓ Instantiation: The process of creating an object.
✓ A constructor is executed to initialize the data.
✓ State: the data that makes up an object is referred to as the object’s state.
❖ Once an object has been instantiated, its state can change.
❖ The state changes whenever you change the value of one of
the object’s properties or public fields.
❖ The state can change when you call a method that affects the data.
❖ You can create two or more instances (objects) of the same class. Each
has its own state.
✓ Object Initializers: create an instance of an object and assign values
without explicitly calling a constructor with parameters.
✓ A class defines a reference type. The variable used to access an object
instantiated from a class contains the address of the object (in memory),
not the actual object.

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 2
Code using Object Initializers (option 3 below)
Assume a class called Student with properties ID (int), Name (string)
and Fulltime (bool). Assume 2 constructors:
public Student(){} // default
public Student(int, string, bool) // 1 parameter for each field

Options to instantiate (create an object):


// call default const
1) Student s1 = new Student();

// call custom const


2) Student s2 = new Student(24, “Jan”, true);

// call def const and initializes (calls set of property)


3) Student s3 = new Student {ID = 17, Name = “bob”,
Fulltime = false};

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 3
Field (variable defined at class level) Declarations
private int quantity; // A private field
public decimal price; // A public field
public readonly int limit = 90; // A public read-only field

Access Modifiers:
Private → can only be used in the class that defines it.
Public → can be accessed by other classes.
Others: introduced in chapter 14

Read-only field: Use keyword readonly in declaration


→ Similar to a constant whose value is set at compile time
→ Readonly value is set at run time
→ Field’s value can be retrieved but it cannot be changed
→ Its value can be set when you declare it (above) or in
the code for a constructor.

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 4
The syntax for coding a public property
public type PropertyName
{
[get { get accessor code }]
[set { set accessor code }]
}
A read/write property Accessors:
public string Code Get → request to retrieve
property values
{
Set → request to set the
get { return code; } Property value
set { code = value; }
}
}

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 5
Read-Only and Write-Only Properties
A read-only property – only has a get
public decimal DiscountAmount
{
get
{
discountAmount = subtotal * discountPercent;
return discountAmount;
}
}

A write-only property – only has a set


public decimal DiscountAmount
{
set
{
if (value > 99.9) discountAmount = value;
}
}

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 6
A read-only property
public decimal DiscountAmount
{
get
{
return subtotal * discountPercent;
}
}

The same property using an expression body


public decimal DiscountAmount => subtotal * discountPercent;

=>Lambda Operator (goes to).


Simplifies the code.
More in chapter 13.

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 7
Overloading
Methods

✓ Code two or more methods with the same name but unique combinations
of parameters sent.
✓ Each overloaded method has a unique signature.
❖ Either a different number of parameters or
❖ At least one of the parameters has a different data type
❖ Names of parameters are not part of the signature
❖ Return type is not part of the signature for overloading
✓ WHY?
❖ More than one way to invoke/ call/ transfer execution to a method.

✓ When typing overloaded method, up and down arrows appear to the left
of the argument list to indicate the method is overloaded.

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 8
The syntax for coding a public method
public returnType MethodName([parameterList])
{
statements
}

A method that accepts parameters


public string GetDisplayText(string sep)
{
return code + sep + price.ToString("c") + sep
+ description;
}

An overloaded version of the method


public string GetDisplayText()
{
return code + ", " + price.ToString("c") + ", "
+ description;
}

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 9
Statements that call the GetDisplayText method
lblProduct.Text = product.GetDisplayText("\t");
lblProduct.Text = product.GetDisplayText();

How the IntelliSense feature lists


overloaded methods

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 10
Constructor Rules
✓ Has same name as Class and can be overloaded
✓ Must have public as access modifier
✓ Cannot specify a return type
✓ Constructor with no executable statements → uses default values below
✓ Can call another method to set initial values

Data type Default value


All numeric types 0
Boolean false
Char null
Object null
Date 12:00 a.m. on January 1, 0001

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 11
A constructor with no parameters
public Product()
{
}

A constructor with three parameters


public Product(string incode, string indescription,
decimal inprice)
{
Code =incode;
Description = indescription;
Price = inprice;
}

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 12
A constructor with one parameter
public Product(string incode)
{
Product p = ProductDB.GetProduct(incode);
this.Code = p.Code;
this.Description = p.Description;
this.Price = p.Price;
}

Statements that call these constructors


Product product1 = new Product();
Product product2 = new Product("CS15",
"Murach's C# 2015", 56.50m);
Product product3 = new Product(txtCode.Text);

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 13
Static Members
✓ Members of a class include fields, properties and methods.
✓ Static members can be accessed without creating an instance of a class.

public class Student


{
private int a;
private static int b = 1000;
}

✓ Put static keyword on member declaration.


✓ Useful for incrementing a unique property (retains the value).
✓ Constants by definition are static, cannot put keyword static with const.

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 14
Static Class
✓ More common → static and non-static members of classes.
✓ You cannot access a static member from the variable that refers to the
instance of the class (object). You access it only by coding the name of the
class.
✓ Static class:
❖ Only has static members and methods
❖ Cannot be instantiated
❖ Cannot be inherited further
❖ Useful for helper or utility methods that are generic in nature (data
validation, file access)

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 15
A class that contains static members
public static class Validator
{
private static string title = "Entry Error";

public static string Title


{
get
{
return title;
}
set
{
title = value;
}
}

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 16
A class that contains static members (cont.)
public static bool IsPresent(TextBox textBox)
{
if (textBox.Text == "")
{
MessageBox.Show(textBox.Tag
+ " is a required field.", Title);
textBox.Focus();
return false;
}
return true;
}

Textbox.Tag property can be


useful to store the name of what is
stored in the textbox ie. Code

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 17
Code that uses static members
if ( Validator.IsPresent(txtCode) &&
Validator.IsPresent(txtDescription) &&
Validator.IsPresent(txtPrice) )
isValidData = true;
else
isValidData = false;

A using directive for the Validator class


using static ProductMaintenance.Validator;

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 18
Using live code analysis to generate a class
-Right-click: Quick Action

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 19
Using live code analysis
to generate a method stub

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 20
A class diagram that shows two of the classes

Found under
Solution
Explorer
(once installed)

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 21
A Peek Definition window with the code for
the GetDisplayText method:
Right-click on member (method or property) in
Code window, select Peek Definition

© 2016, Mike Murach & Associates, Inc.


Murach's C# 2015 C12, Slide 22

You might also like