C# Classes
C# Programming
Quincy College
Fall 2021
Robert I. Pitts
Controlling access to classes and members
Creating code libraries
Indexers
Object initializers and anonymous objects
Structures and nullable types
LINQ (Language-Integrated Query)
Fall 2021C# Programming 2
May restrict set accessor for property, or
remove accessor altogether
const: only give value when list variable
◦ const variables are implicitly static
readonly: cannot change instance variable
after constructor (mark all to make immutable)
internal: accessible in same assembly, not
outside assembly (default for classes)
◦ Assembly: program (.exe) or code library (.dll)
Fall 2021C# Programming 3
Classes usable by many projects belong in library
1. New Project > Class Library (.NET Framework)
2. Add public class
◦ May have non-public supporting classes
3. Place in own namespace
4. Compile to dynamically-linked library (.dll)
5. Refer to library in application
◦ Project > Add reference… > Browse
6. Add using directive for library namespace
Fall 2021C# Programming 4
May access instance variable or non-static
method in class via the this reference
public Rect(double width, double height)
{
this.width = width;
this.height = height;
}
◦ Avoids instance variable/parameter conflicts
Also, to call one constructor from another
public Rect(double len) // a square
: this(len, len)
{ }
◦ Called “constructor initializer”
Fall 2021C# Programming 5
Can give array-like indexing to class
public double this[int index]
{
…
set {
if (index == 0)
width = value;
else if (index == 1)
height = value;
}
}
…
Rect rect1 = new Rect(6.7);
rect1[0] = 5.6;
Fall 2021C# Programming 6
Type of indexType stores/gives
Constructors limit how can initialize objects
Student stud1 = new Student(id1);
To give values to other instance variables, use
properties later
stud1.Name = “Jones,Bart”;
stud1.Gpa = 3.0;
Object initializer is concise way to do both
Student stud1 = new Student(id1) {
Name = “Jones,Bart”, Gpa = 3.0
};
Fall 2021C# Programming 7
Initializer syntax allows objects without explicit class
(“anonymous type”)
Use var since no data type can be provided
var stud1 = new {
Id = id1,
Name = “Jones,Bart”,
Gpa = 3.0
};
All properties public and immutable
ToString() shows property values
Equals() compares all property values
Fall 2021C# Programming 8
no class name listed
Use class for type of data in another class
◦ Called composition (“has-a” relationship)
◦ Limited to public interface (“services”) of class
Add operations with extension method
static class StudentExtensions
{
public static bool InternQual(
this Student stud)
{
return stud.Gpa >= 3.0;
}
…
Usage: stud1.InternQual();
Fall 2021C# Programming 9
write as static
method in static
top-level class
Classes are reference types
class Coord
{
private int x, y;
// c-tor
}
Coord pos = new Coord(10, 20);
Structures (struct) like class but value types
◦ Question: if change class
above to struct?
◦ Answer: object stored in variable
Fall 2021C# Programming 10
pos
x: 10
y: 20
pos
x: 10
y: 20
Value can store null if made nullable
◦ Add question mark (?) to end of data type
Examples:
DateTime? when = new DateTime(…);
int? z = -1;
z = null; // assign null for int
Properties:
z.HasValue // not null (bool)?
z.Value // value if not null
Accessing Value property when variable holds null
causes exception
Fall 2021C# Programming 11
Must determine that nullable type is not null before
using Value
int? z = 5;
int y;
Check HasValue property via if
if (z.HasValue)
y = z.Value;
Test directly against null (conditional operator, ?:)
y = z != null ? z.Value : 0;
Use C# null coalescing operator (??)
y = z ?? 0; // if not null, value of z, else 0
Fall 2021C# Programming 12
Enumeration values not always mutually exclusive
[Flags]
enum BookFormat
{
NoFormat = 0,
HardCopy,
PaperBack
}
May assign multiple use bitwise logical operators
BookFormat format = BookFormat.HardCopy;
◦ Useful ops: OR (|), AND (&), NOT (~), XOR (^)
Fall 2021C# Programming 13
HardCopy = 1,
PaperBack = 2
= BookFormat.HardCopy
| BookFormat.PaperBack;
PaperBack = 2,
Parchment = 4 // powers of 2
Query different sources of data (array, database)
using SQL-like syntax
Example:
DateTime[] meetings = …
var afternoonMeetings =
from value in meetings
where value.Hour > 12
orderby value.DayOfWeek
select value;
May then iterate through results via foreach
Fall 2021C# Programming 14
Takes on each
item’s value
Place reusable code in dynamic link library (.dll)
Use this to call other constructors, add
subscripting (indexer), extend methods
For anonymous class, list properties after new
Structures are like classes, but are value types
Fall 2021C# Programming 15
Adding extra element to array so that start with
index 1
Abstract data type (ADT): Information
hiding/data abstraction
Class View and Object Browser
Garbage collection and destructors
Fall 2021C# Programming 16