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

C# UNIT 3

This document provides an overview of C# structures, enums, arrays, and string operations. It explains the differences between structs and classes, how to define and use enums, and the functionality of arrays including initialization and manipulation. Additionally, it covers string operations, the use of StringBuilder, and file handling methods in C#.

Uploaded by

Gulam Ansari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

C# UNIT 3

This document provides an overview of C# structures, enums, arrays, and string operations. It explains the differences between structs and classes, how to define and use enums, and the functionality of arrays including initialization and manipulation. Additionally, it covers string operations, the use of StringBuilder, and file handling methods in C#.

Uploaded by

Gulam Ansari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

UNIT 3

C SHARP – STRUCT, ENUM, ARRAYS AND STRING

STRUCT TYPES, STRUCT DECLARATION


The struct (structure) is like a class in C# that is used to store data. However, unlike classes, a
struct is a value type. In C#, structure is defined using struct keyword. Using struct keyword
one can define the structure consisting of different data types in it. A structure can also
contain constructors, constants, fields, methods, properties, indexers and events etc.
Syntax :
Access_Modifier struct structure_name
{
// Fields
// Parameterized constructor
// Constants
// Properties
// Indexers
// Events
// Methods etc.
}
Example :
using System;
struct Books {
public string title;
public string author;
};
public class testStructure {
public static void Main(string[] args) {
Books Book1;
Books Book2;
Book1.title = "C Programming";
Book1.author = "Nuha Ali";
Book2.title = "Telecom Billing";
Book2.author = "Zara Ali";
Console.WriteLine( "Book 1 title : "+Book1.title);
Console.WriteLine("Book 1 author : "+ Book1.author);
Console.WriteLine("Book 2 title : "+ Book2.title);
Console.WriteLine("Book 2 author : "+ Book2.author);
Console.ReadKey();
}
}
Difference Between Structures and Class

Category Structure Class

Data Type Value Type Reference type

Assignment Operation Copies the value Copies the reference

Parameterless Constructors Not Allowed Allowed

Inheritance Not supported Always supported

STRUCT INTERFACE
A structure can also hold constructors, constants, fields, methods, properties, indexers, and
events, etc.
Syntax:
public struct
{
// Fields
// Methods
}
Interface is like a class, it can also have methods, properties, events, and indexers as its
members. But interfaces can only have the declaration of the members. The implementation of
the interface’s members will be given by the class that implements the interface implicitly or
explicitly. Or we can say that it is the blueprint of the class.
Syntax:
interface interface_name
{
// Method Declaration in interface
}
Syntax for struct interface
struct code: interface1, interface2
{
// Method definition for interface method
// Method definition for interface method
}
Example:

using System;

interface interface1

// Declaration of Method

void MyMethod1();

// Interface 2

interface interface2

void MyMethod2();

struct code : interface1, interface2

void MyMethod1()

Console.WriteLine("interface1.Method()");

}
void MyMethod2()

Console.WriteLine("interface2.Method()");

class program{

public static void Main(String[] args)

interface1 M1;

interface2 M2;

// Create objects

M1 = new code();

M2 = new code();

M1.MyMethod1();

M2.MyMethod2();

Output:
interface1.Method() is called
interface2.Method() is called
ENUMS, ENUMERATOR BASE TYPE

An enum is a special "class" that represents a group of constants (unchangeable/read-only


variables).To create an enum, use the enum keyword (instead of class or interface), and
separate the enum items with a comma:

enum Level

Low,

Medium,

High

You can access enum items with the dot syntax:

Level myVar = Level.Medium;

Console.WriteLine(myVar);
ENUM MODIFIERS
In C#, the only modifiers allowed on an enum declaration are access modifiers like "public",
"protected", and "private", which control the visibility of the enum type within your code,
similar to how you would use them with classes.Access modifiers define which parts of your
code can access the enum. Example :
public enum DayOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday };
ENUM MEMBERS
The body of an enum type declaration defines zero or more enum members, which are the
named constants of the enum type. No two enum members can have the same name.
Example :
using System;
enum Color
{
Red,
Green = 10,
Blue = 11
}
class Test
{
static void Main()
{
Console.WriteLine(StringFromColor(Color.Red));
Console.WriteLine(StringFromColor(Color.Green));
Console.WriteLine(StringFromColor(Color.Blue));
}
static string StringFromColor(Color c)
{
switch (c)
{
case Color.Red:
return $"Red = {(int) c}";
case Color.Green:
return $"Green = {(int) c}";
case Color.Blue:
return $"Blue = {(int) c}";
default:
return "Invalid color";
}
}
}

Output:

Red = 0
Green = 10
Blue = 11

ENUM VALUES AND OPERATIONS

Each enum type defines a distinct type; an explicit enumeration conversion is required to
convert between an enum type and an integral type, or between two enum types. Any value of
the underlying type of an enum can be cast to the enum type, and is a distinct valid value of
that enum type.
The following operators can be used on values of enum types:

● comparison
● Addition
● Subtraction
● Bitwise

CONCEPT OF ARRAYS

Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.To declare an array, define the variable type with square brackets:

string[] cars;

We have now declared a variable that holds an array of strings.To insert values to it, we can
use an array literal - place the values in a comma-separated list, inside curly braces:

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};

ACCESS THE ELEMENTS OF AN ARRAY


You access an array element by referring to the index number.This statement accesses the
value of the first element in cars:
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

Console.WriteLine(cars[0]);

PASSING ARRAY AS PARAMETERS


An array can also be passed to a method as an argument or parameter. A method processes
the array and returns output. Passing array as parameter in C# is pretty easy as passing other
value as a parameter. Just create a function that accepts an array as argument and then
processes them. The following demonstration will help you to understand how to pass an
array as an argument in C# programming.
Example :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace array_parameter
{
class Program
{
static void printarray(int[] newarray)
{
int i, sum = 0;
Console.Write("\n\nYou entered:\t");
for (i = 0; i < 4; i++)
{
Console.Write("{0}\t", newarray[i]);
sum = sum + newarray[i];
}

Console.Write("\n\nAnd sum of all value is:\t{0}", sum);


Console.ReadLine();
}

static void Main(string[] args)


{
int[] arr = new int[4];
int i;
for (i = 0; i < 4; i++)
{
Console.Write("Enter number:\t");
arr[i] = Convert.ToInt32(Console.ReadLine());
}
// passing array as argument
Program.printarray(arr);
}
}
}

ARRAY INITIALIZATION

Declaring an array does not initialize the array in the memory. When the array variable is
initialized, you can assign values to the array.Array is a reference type, so you need to use
the new keyword to create an instance of the array. For example,

double[] balance = new double[10];


int[] arr1 = new int[5];
int[] arr2 = new int[5]{1, 2, 3, 4, 5};
int[] intArray3 = {1, 2, 3, 4, 5};

ARRAY LIST (ADDING, DELETING, SEARCHING DATA FROM ARRAY LIST)

In C#, the ArrayList is a non-generic collection of objects whose size increases dynamically.
It is the same as Array except that its size increases dynamically.An ArrayList can be used to
add unknown data where you don't know the types and the size of the data.

1.ADD : Add() method adds single elements at the end of ArrayList.


Example :

using System;

using System.Collections;

namespace abc

class Program

static void Main(string[] args)

ArrayList arrlist = new ArrayList();

arrlist.Add("Welcome");

arrlist.Add("TO");

arrlist.Add("C#");

foreach (var item in arrlist)

Console.WriteLine(item);

Console.ReadLine();

2.DELETE : Remove() method removes the specified element from the ArrayList.

using System;

using System.Collections;

namespace abc
{

class Program

static void Main(string[] args)

ArrayList arrlist = new ArrayList();

arrlist.Add("Welcome");

arrlist.Add("TO");

arrlist.Add("C#");

arrlist.Remove("C#");

foreach (var item in arrlist)

Console.WriteLine(item);

Console.ReadLine();

3.SEARCH: Searches for the specified Object and returns the zero-based index of the first
occurrence within the entire ArrayList.

using System;

using System.Collections;

using System.Collections.Generic;

class code {

public static void Main()


{

ArrayList al = new ArrayList();

al.Add("A");

al.Add("B");

al.Add("C");

al.Add("D");

al.Add("E");

if (al.Contains("E"))

Console.WriteLine("Yes, exists at index " + al.IndexOf("E"));

else

Console.WriteLine("No, doesn't exists");

STRING OPERATIONS

Strings are used for storing text. A string variable contains a collection of characters
surrounded by double quotes. Create a variable of type string and assign it a value:

string greeting = "Hello";

A string variable can contain many words, if you want:

string greeting2 = "Nice to meet you!";

STRING FUNCTIONS
Function Description
Combines multiple strings into one.
Concat()

Length Measures the length of a string (number of characters).


ToUpper() Converts a string to uppercase.
ToLower() Converts a string to lowercase.
Substring() Extracts a portion of a string.
Function Description
Replace() Replaces specific characters or words in a string.

Example :
1 . Concat() : string str1 = "Hello, ";
string str2 = "World!";
string result = string.Concat(str1, str2);

2. length() : string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

Console.WriteLine("The length of the txt string is: " + txt.Length);

3 . ToUpper() and ToLower() :

string txt = "Hello World";

Console.WriteLine(txt.ToUpper());

Console.WriteLine(txt.ToLower());

4 . Substring () :
string originalString = "Hello, World!";
string extractedSubstring = originalString.Substring(7);

Console.WriteLine(extractedSubstring);

5. Replace() :
string sentence = "The quick brown fox jumps over the lazy dog";
string newSentence = sentence.Replace("fox", "cat");

Console.WriteLine(newSentence);

CONVERTING OBJECTS TO STRING

In C# object is the main class and it’s also the parent or root of all the classes hence c# is the
object-oriented language. We can convert the object to other data types like string, arrays, etc.
Here we convert the object to a string by using the Object.toString() method for translating
the object to string values.

Example :
using System;
using demo;
namespace demo
{
public class demo1
{
public void exam()
{
Console.WriteLine("Welcome To My Domain its the first example for C# programming
language we want to convert the object to string values");
}
}
}
public class demo2
{
public static void Main()
{
object firstobj = new demo1();
Console.WriteLine(firstobj.ToString());
}

STRING BUILDER
StringBuilder is a Dynamic Object. It doesn’t create a new object in the memory but
dynamically expands the needed memory to accommodate the modified or new
string.A String object is immutable, i.e. a String cannot be changed once created. To avoid
string replacing, appending, removing or inserting new strings in the initial string C#
introduce StringBuilder concept.

Declaration and Initialization of StringBuilder


StringBuilder can be declared and initialized the same way as class,
StringBuilder s = new StringBuilder();
or

StringBuilder s = new StringBuilder("hi");


“s” is the object of StringBuilder class. Also, we can pass a string value(here “hi”) as an
argument to the constructor of StringBuilder.

StringBuilder.Insert(int index, string This method inserts the string at specified index
value) in StringBuilder object.

StringBuilder.Remove(int start, int This method removes the specified number of


length) characters from the current StringBuilder object.

This method is used to replace characters within


StringBuilder.Replace(old_val, the StringBuilder object with another specified
new_val) character.

Example :

// Adding element in StringBuilder Object

using System;

using System.Text;

class code

public static void Main()

StringBuilder s = new StringBuilder("HELLO ", 20);

s.Append("program");

s.AppendLine("C#");

s.Append("C# program");

Console.WriteLine(s);

FILE AND FOLDER OPERATIONS


The File class from the System.IO namespace, allows us to work with files:

Example

using System.IO; // include the System.IO namespace

File.SomeFileMethod(); // use the file class with methods

The File class has many useful methods for creating and getting information about files. For
example:

Method Description

Append Appends text at the end of an existing file


Text()

Copy() Copies a file

Create( Creates or overwrites a file


)

Delete( Deletes a file


)

Exists() Tests whether the file exists

ReadAl Reads the contents of a file


lText()

Replac Replaces the contents of a file with the contents of another file
e()
WriteA Creates a new file and writes the contents to it. If the file already exists, it will be overwritten.
llText()

READING AND WRITING TEXT FILES


Write To a File and Read It

In the following example, we use the WriteAllText() method to create a file named
"filename.txt" and write some content to it. Then we use the ReadAllText() method to read
the contents of the file:

Example

using System.IO; // include the System.IO namespace

string writeText = "Hello World!"; // Create a text string

File.WriteAllText("filename.txt", writeText); // Create a file and write the content of


writeText to it

string readText = File.ReadAllText("filename.txt"); // Read the contents of the file

Console.WriteLine(readText); // Output the content

The output will be:

Hello World!

READING AND WRITING BINARY FILES


Reading and writing binary files in C# can be done using the System.IO namespace, which
provides the BinaryReader and BinaryWriter classes. These classes allow you to work with
binary data in files. Below are examples of how to read and write binary files in C#.

Writing a Binary File

Here is an example of how to write binary data to a file using BinaryWriter:


using System;
using System.IO;
class Program
{
static void Main()
{
// File path
string filePath = "example.bin";

// Create a FileStream to write binary data


using (FileStream fs = new FileStream(filePath, FileMode.Create))
using (BinaryWriter writer = new BinaryWriter(fs))
{
// Write data to the file
writer.Write(42); // Write an integer
writer.Write(3.14); // Write a double
writer.Write("Hello, world!"); // Write a string
}

Console.WriteLine("Binary file written successfully.");


}
}
In this example, we create a FileStream to open the file for writing (FileMode.Create), then
wrap it with a BinaryWriter to write binary data. We write an integer, a double, and a string.

Reading a Binary File

Here is an example of how to read binary data from a file using BinaryReader:
csharp
Copy
using System;
using System.IO;

class Program
{
static void Main()
{
// File path
string filePath = "example.bin";

// Open the file for reading


using (FileStream fs = new FileStream(filePath, FileMode.Open))
using (BinaryReader reader = new BinaryReader(fs))
{
// Read data from the file
int intValue = reader.ReadInt32(); // Read an integer
double doubleValue = reader.ReadDouble(); // Read a double
string stringValue = reader.ReadString(); // Read a string

// Output the values read from the file


Console.WriteLine($"Integer: {intValue}");
Console.WriteLine($"Double: {doubleValue}");
Console.WriteLine($"String: {stringValue}");
}
}
}
In this example, we use BinaryReader to read the same types of data that we wrote in the
previous example. The ReadInt32, ReadDouble, and ReadString methods are used to read the
respective types of data from the binary file.
Important Notes:

1. Endianness: When writing or reading binary data, consider endianness (the byte
order). In most modern systems, little-endian is used, but when dealing with cross-
platform systems or specific hardware, it might differ.
2. Positioning: The BinaryReader and BinaryWriter classes read/write sequentially, so
they keep track of the current position within the file.
3. File Mode: When opening files, you can use different FileMode options (Create,
Open, Append, etc.) to define how the file is opened.

You might also like