Foundation_Structs, Enums, Exceptions & Files


Reference:https://www.sololearn.com/Play/CSharp

Structs

A struct type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory. The following example shows a simple struct declaration:

struct Book {
  public string title;  
  public double price;
  public string author;
}

Structs share most of the same syntax as classes, but are more limited than classes.
Unlike classes, structs can be instantiated without using a new operator.

static void Main(string[] args) {
  Book b;
  b.title = "Test";
  b.price = 5.99;
  b.author = "David";

  Console.WriteLine(b.title);
  //Outputs "Test"
}

Structs do not support inheritance and cannot contain virtual methods.

Structs can contain methods, properties, indexers, and so on. Structs cannot contain default constructors (a constructor without parameters), but they can have constructors that take parameters. In that case the new keyword is used to instantiate a struct object, similar to class objects.
For example:

struct Point {
  public int x;
  public int y;
  public Point(int x, int y) {
    this.x = x;
    this.y = y;
  }
}
static void Main(string[] args) {
  Point p = new Point(10, 15);
  Console.WriteLine(p.x);
  // Outputs 10
 }

Structs vs Classes

In general, classes are used to model more complex behavior, or data, that is intended to be modified after a class object is created. Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created. Consider defining a struct instead of a class if you are trying to represent a simple set of data.

All standard C# types (int, double, bool, char, etc.) are actually structs.

Practice

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SoloLearn
{
    class Program
    {
        static void Main(string[] args)
        {
            int length = Convert.ToInt32(Console.ReadLine());
            int width = Convert.ToInt32(Console.ReadLine());
            int height = Convert.ToInt32(Console.ReadLine());

            Cuboid cuboid = new Cuboid(length, width, height);

            Console.WriteLine("Volume: " + cuboid.Volume());
            Console.WriteLine("Perimeter: " + cuboid.Perimeter());
        }
    }
    struct Cuboid
    {
        public int length;
        public int width;
        public int height;

        //create a constructor
        public Cuboid(int L,int W,int H){
         this.length=L;
         this.width=W;
         this.height=H;
         
        }
        
        //complete this method
        public int Volume()
        {
            return length*width*height;
        }
        //complete this method
        public int Perimeter()
        {
            return 4*length+4*width+4*height;
        }
    }
}

Enums

The enum keyword is used to declare an enumeration: a type that consists of a set of named constants called the enumerator list.
By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.
For example, in the following enumeration, Sun is 0, Mon is 1, Tue is 2, and so on:

enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat}; 

You can also assign your own enumerator values:

enum Days {Sun, Mon, Tue=4, Wed, Thu, Fri, Sat}; 

In the example above, the enumeration will start from 0, then Mon is 1, Tue is 4, Wed is 5, and so on. The value of the next item in an Enum is one increment of the previous value.
Note that the values are comma separated.
You can refer to the values in the Enum with the dot syntax.
In order to assign Enum values to int variables, you have to specify the type in parentheses:

enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; 

static void Main(string[] args) {
  int x = (int)Days.Tue;
  Console.WriteLine(x);
  //Outputs 2
}

Enums are often used with switch statements.
For example:

enum TrafficLights { Green, Red, Yellow };

static void Main(string[] args) {
  TrafficLights x = TrafficLights.Red;
  switch (x) {
    case TrafficLights.Green:
      Console.WriteLine("Go!");
      break;
    case TrafficLights.Red:
      Console.WriteLine("Stop!");
      break;
    case TrafficLights.Yellow:
      Console.WriteLine("Caution!");
      break;
  }
  //Outputs "Stop!"
}

Practice

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SoloLearn
{
    class Program
    {
        static void Main(string[] args)
        {

            Player player1 = new Player(Difficulty.Easy);
            Player player2 = new Player(Difficulty.Medium);
            Player player3 = new Player(Difficulty.Hard);
        }
    }
    
    /*
    Easy => "You have 3 minutes 45 seconds"
    Medium = > "You have 3 minutes 20 seconds"
    Hard => "You have 3 minutes"
    */

    class Player
    {
        public Player(Difficulty x)
        {
            //your code goes here
            switch(x){
             case Difficulty.Easy:
             Console.WriteLine("You have 3 minutes 45 seconds");
break;
             case Difficulty.Medium:
             Console.WriteLine("You have 3 minutes 20 seconds");
break;
             case Difficulty.Hard:
             Console.WriteLine("You have 3 minutes");
break;
            }
        }
    }
     enum Difficulty
    {
        Easy,
        Medium,
        Hard
    };
}

Exceptions

An exception is a problem that occurs during program execution. Exceptions cause abnormal termination of the program.
An exception can occur for many different reasons. Some examples:

  • A user has entered invalid data.
  • A file that needs to be opened cannot be found.
  • A network connection has been lost in the middle of communications.
  • Insufficient memory and other issues related to physical resources.

Handling Exceptions

C# provides a flexible mechanism called the try-catch statement to handle exceptions so that a program won’t crash when an error occurs.

try {
  int[] arr = new int[] { 4, 5, 8 };
  Console.Write(arr[8]);
}
catch(Exception e) {
  Console.WriteLine("An error occurred");
}
//Outputs "An error occurred"

The code that might generate an exception is placed in the try block. If an exception occurs, the catch blocks is executed without stopping the program.
The type of exception you want to catch appears in parentheses following the keyword catch.
We use the general Exception type to handle all kinds of exceptions. We can also use the exception object e to access the exception details, such as the original error message (e.Message):

try {
  int[] arr = new int[] { 4, 5, 8 };
  Console.Write(arr[8]);
}
catch(Exception e) {
  Console.WriteLine(e.Message);
}
// Index was outside the bounds of the array.

Handling Multiple Exceptions

A single try block can contain multiple catch blocks that handle different exceptions separately.
Exception handling is particularly useful when dealing with user input.

int x, y;
try {
  x = Convert.ToInt32(Console.Read());
  y = Convert.ToInt32(Console.Read());
  Console.WriteLine(x / y);
}
catch (DivideByZeroException e) {
  Console.WriteLine("Cannot divide by 0");
}
catch(Exception e) {
  Console.WriteLine("An error occurred");
}

The following exception types are some of the most commonly used:
FileNotFoundException,
FormatException,
IndexOutOfRangeException,
InvalidOperationException,
OutOfMemoryException.

Finally

An optional finally block can be used after the catch blocks. The finally block is used to execute a given set of statements, whether an exception is thrown or not.
For example:

int result=0;
int num1 = 8;
int num2 = 4;
try {
  result = num1 / num2;
}
catch (DivideByZeroException e) {
  Console.WriteLine("Error");
}
finally {
  Console.WriteLine(result);
}

Working with Files

Writing to Files

The System.IO namespace has various classes that are used for performing numerous operations with files, such as creating and deleting files, reading from or writing to a file, closing a file, and more.
The File class is one of them. For example:

string str = "Some text";
File.WriteAllText("test.txt", str);

The WriteAllText() method creates a file with the specified path and writes the content to it. If the file already exists, it is overwritten.
The code above creates a file test.txt and writes the contents of the str string into it.

To use the File class you need to use the System.IO namespace: using System.IO;

Reading from Files

You can read the content of a file using the ReadAllText method of the File class:

string txt = File.ReadAllText("test.txt");
Console.WriteLine(txt); 

This will output the content of the test.txt file.
The following methods are available in the File class:
AppendAllText() - appends text to the end of the file.
Create() - creates a file in the specified location.
Delete() - deletes the specified file.
Exists() - determines whether the specified file exists.
Copy() - copies a file to a new location.
Move() - moves a specified file to a new location
All methods automatically close the file after performing the operation.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值