2. Structures
C# allows you to group several variables together into a single item known as
a structure.
Structures in C# are capable of much more than we discuss. For example, in
addition to declaring fields, you can also write methods inside of structures.
struct Student
{
public int rno;
public string name;
public double marks;
} //No need of Semi-Collon
Student st1,st2; //Structure Variable Declararion
The default accessibility is private.
3. Structures
In C#, a structure (struct) is a value type that is used to create lightweight
objects. It is similar to a class but has some differences.
struct Student
{
public string Name;
public int Age;
// Constructor
public Student(string name, int age)
{
Name = name;
Age = age;
}
// Method
public void Display()
{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
}
4. class Program
{
static void Main()
{
Student student1 = new Student("Ali", 20); // Using constructor
student1.Display();
Student student2; // No 'new' needed
student2.Name = "Sara";
student2.Age = 22;
student2.Display();
}
}
5. Key Differences: struct vs class
Feature struct (Structure) class
Type Value Type (stored in stack)
Reference Type (stored
in heap)
Memory More efficient for small data
Better for complex
objects
Inheritance
❌ No inheritance (but can
implement interfaces)
✅ Supports inheritance
Default Constructor
❌ Cannot define
parameterless constructor in
C# < 10
✅ Allowed
Nullability Cannot be null (unless struct?) Can be null
6. Using the new Operator to Create Structure Instances
When you create a structure object with a simple declaration statement, as
previously shown, the object’s fields are uninitialized, and if you attempt to use
any of them before assigning them a value, a compiler error occurs. As an
alternative, you can use the new operator to create an instance of a structure,
as shown here:
Student st = new Student();
This is the recommended technique for creating structure instances because the
new operator not only creates the instance in memory, but it also initializes the
object’s fields with the default value of 0. (If the structure contains any fields
that are reference variables, they are initialized with the special value null.)
7. Once you have created an instance of a structure, you can access its fields using
the dot operator (a period).
Accessing a Structure’s Fields
Assigning One Structure Object to Another
You can use the assignment operator (=) to assign one structure object to
another. For example, assume that st1 and st2 are both instances of the Student
structure. The following statement assigns st1 to st2:
st2 = st1;
After this statement executes, the st2 object’s fields contain the same values as
the st1 object’s fields.
8. Structure objects can be passed by value or by reference. Normally, structure
objects are passed by value. The parameter variable contains a copy of the
argument, and any changes that are made to the parameter do not affect the
original argument. If the receiving method needs to change the contents of the
original argument, however, the ref or out keyword can be used in the
parameter declaration.
Passing Structure Objects to Methods
As with other types of objects, you can pass a structure object as an argument
to a method. The following code shows a method named DisplayResult that
has been written to accept an instance of the Student structure as an
argument:
private void DisplayResult(Student st)
{
Console.WriteLine($”Roll No: {st.rno}
Name : {st.name}
Marks : {st.marks}”;
}
9. private void DisplayResult(ref Student st)
{
Console.WriteLine($”Roll No: {st.rno}
Name : {st.name}
Marks : {st.marks}”;
}
Passing Structure By Reference
10. namespace Structures {
internal class Program
{
struct Students
{
public int rno, marks;
public string name;
}
static void Main(string[] args)
{
Students st1 = new Students(); ;
Students st2 = new Students();
st1.rno = 20;
st1.name = "Ali";
st1.marks = 300;
st2 = st1;
}
}
}
11. namespace Structures
{
internal class Program
{
struct Students
{
public int rno, marks;
public string name;
}
static void DisplayResult(Students st)
{
st.rno = st.rno + 3;
Console.WriteLine("New Roll No : " + st.rno);
}
static void Main(string[] args)
{
Students st1 = new Students();
st1.rno = 20;
st1.name = "Ali";
st1.marks = 300;
DisplayResult(st1);
Console.WriteLine("Old Roll No : " + st1.rno);
}
}
}
Call by Value
12. Call by Reference
namespace Structures
{
internal class Program
{
struct Students
{
public int rno, marks;
public string name;
}
static void DisplayResult(ref Students st)
{
st.rno = st.rno + 3;
Console.WriteLine("New Roll No : " + st.rno);
}
static void Main(string[] args)
{
Students st1 = new Students();
st1.rno = 20;
st1.name = "Ali";
st1.marks = 300;
DisplayResult(ref st1);
Console.WriteLine("Old Roll No : " + st1.rno);
}
}
}
13. Comparing Structure Objects
You cannot perform comparison operations directly on structure objects. For
example, assume that st1 and st2 are instances of the Students structure.
The following statement will cause an error:
if (st1 == st2) // Error!
Arrays of Structure Objects
Students[] st1 = new Students[10];
st1[0].rno = 20;
st1[0].name = "Ali";
st1[0].marks = 300;
15. The DateTime and TimeSpan Structures
In the .NET Framework, the DateTime structure stores a date, a time, or both.
The TimeSpan structure stores information about a time interval.
The DateTime structure, which is defined in the .NET Framework, allows you
to create objects that store data about an instant in time. A DateTime object
stores both date and time. Internally, the date and time values are stored in
the following properties:
▪ Month—an integer in the range of 1–12
▪ Day—an integer in the range of 1–31
▪ Year—an integer in the range of 1–9999
▪ Hour—an integer in the range of 0–23
▪ Minute—an integer in the range of 0–59
▪ Second—an integer in the range of 0–59
▪ Millisecond—an integer in the range of 0–999
16. Notice that the Hour property is set according to the 24-hour clock.
There are several ways to create an instance of the DateTime structure. The following
statement creates a DateTime instance named dt , set to the default date January 1,
0001 and the default time 12:00:00 AM, 0 milliseconds:
DateTime dt = new DateTime();
You can change the individual date and time properties as shown in the following code sample:
DateTime dt = new DateTime();
dt.Month = 12;
dt.Day = 15;
dt.Year = 2019;
dt.Hour = 13;
dt.Minute = 30;
dt.Second = 0;
dt.Millisecond = 0;
17. When you create a DateTime instance, you can optionally initialize it with a
specific date, time, or both. Here are three general formats:
DateTime instanceName = new DateTime(Year, Month, Day);
DateTime instanceName = new DateTime(Year, Month, Day, Hour, Minute, Second);
DateTime instanceName = new DateTime(Year, Month, Day, Hour, Minute, Second,
Millisecond);
The values for Year , Month , Day , Hour , Minute , Second , and Millisecond are integers.
The following example creates a DateTime instance named dt , set to the date September
5, 2023. The Hour, Minute, Second, and Millisecond properties are set to the default value
of 0, which is midnight:
DateTime dt = new DateTime(2023, 9, 5);
18. The following example creates a DateTime instance named dt , set to the date
November 5, 2000, and the time 8:30 AM. The Second property is set to 15, and
the Millisecond property is set to the default value of 0:
DateTime dt = new DateTime(2000, 11, 5, 8, 30, 15);
DateTime dt = new DateTime(2000, 11, 5, 8, 30, 15, 500);
19. Displaying a DateTime Object
You can retrieve any of a DateTime object as whole or individual properties and
use them in your program’s output
DateTime dt = new DateTime(2000, 11, 5);
Console.WriteLine(dt.Month.ToString() + ", " + dt.Year.ToString());
DateTime dt = new DateTime(2000, 11, 5);
Console.WriteLine(dt.ToString());
20. You can use format strings to format it as a short date, long date, short time,
long time, and so on.
Format Description
d
Shows the date only, in short date format which shows the month,
day, and year. An example is 8/23/2019.
D
Shows the date only, in long date format which shows the day of the
week, month, day, and year. An example is Tuesday, August 23,
2019.
t
Shows the time only, in short time format which shows the hours and
minutes. An example is 3:22 PM.
T
Shows the time only, in long time format which shows the hours,
minutes, seconds, and an AM/PM indicator. An example is 3:22:00
PM.
f
This specifier represents the full date and time (long date and short
time) pattern. It displays the date as the long date and the time
without seconds. (dddd, MMMM dd, yyyy h:mm tt)
F
This specifier represents the full date and time (long date and long
time) pattern. It displays the date as the long date and the time
including seconds. (dddd, MMMM dd, yyyy h:mm:ss tt)
22. The DateTime structure also supports the following methods for formatting:
• ToShortDateString() —Returns the date formatted as a short date, which
is the same as ToString("d")
• ToLongDateString() —Returns the date formatted as a long date, which is
the same as ToString("D")
• ToShortTimeString() —Returns the time formatted as a short time, which
is the same as ToString("t")
• ToLongTimeString() —Returns the time formatted as a long time, which is
the same as ToString("D")
23. Getting the Current Date and Time from the System
The expression DateTime.Now gives you the current date and time from the
system.
DateTime currentDate = DateTime.Now;
After this statement is executed, the currentDate object will be set to the
current date, but the object’s time properties will be set to the default value
of 12:00 AM.
DateTime currentDate = DateTime.Today;
24. Converting Strings to DateTime Structures
DateTime.TryParse(string, out targetVariable)
In the general format, string is the string that you want to convert, and
targetVariable is the name of a DateTime object. The method tries to convert the
string argument to a DateTime object. If the conversion is successful, the
converted value is assigned to the targetVariable , and the method returns the
Boolean value true to indicate that the conversion was successful. If the
conversion is not successful, the method stores the default date January 1, 0001
and the default time 12:00:00 AM in the targetVariable and returns the Boolean
value false to indicate that the string could not be converted.
27. The DateTimePicker Control
The DateTimePicker control (found in the Toolbox’s Common Controls group)
provides an easy way for the user to select dates. It is a drop-down control that
displays a small scrollable calendar showing an entire month. The user picks a
date from the calendar and your program retrieves that date as a DateTime
object from the control’s Value property. Initially, the Value property is set to the
current date, and the current date will appear selected in the control’s calendar.
When the user selects a date from a DateTimePicker control, a ValueChanged
event is triggered. If you write a ValueChanged event handler for the control, the
event handler will execute any time a date is selected. To generate a code
template for the ValueChanged event handler, simply double-click the
DateTimePicker control in the Designerwindow.
28. The TimeSpan Structure
The TimeSpan structure allows you to create objects that store data about an
amount of time, such as five days, or 20 hours.
A TimeSpan object stores time values in the following properties:
➢ Days — an integer, positive or negative
➢ Hours — an integer in the range of -23 through 23
➢ Minutes — an integer in the range of −59 through 59
➢ Seconds — an integer in the range of −59 through 59
➢ Milliseconds — an integer in the range of −999 through 999
29. There are several ways to create an instance of the TimeSpan structure. The
following statement creates a TimeSpan instance named tspan , set to the
default value of 0 days, 0 hours, 0 minutes, 0 seconds, and 0 milliseconds:
TimeSpan tspan = new TimeSpan();
You can change the individual properties as shown in the following code sample:
TimeSpan tspan = new TimeSpan();
tspan.Days = 15;
tspan.Hours = 6;
tspan.Minutes = 30;
tspan.Seconds = 10;
tspan.Milliseconds = 500;
30. ref vs out in C#
Both keywords pass arguments by reference, but with critical differences:
ref:
Requires the caller to initialize the variable.
The method can read and modify the value.
Example:
static void Modify(ref int x) { x = x+10; } // Reads + modifies
out:
Ignores the caller’s initial value (even if assigned).
The method must assign a value before returning.
Example:
static void Initialize(out int x) { x = 10; } // Write-only