C # basic

9 minute read

table of contents

–What is C #?

  • Feature
  • HelloWorld
    –Standard input
    –Standard output
    –Variables
    –Random
    –Conditional branch
    –DateTime structure
    –Repeat processing
    –Array
    –List class
    –Multidimensional array
  • Dictionary
    –Method
    –Scope
  • LINQ
    –Class
    –Access modifier
  • static
    –Properties
    –Class inheritance
    –Namespace
    –Exception handling (Exception)

What is C

An object-oriented language that runs on the .NET Framework

HelloWorld

using System;
public class Hello{
	public static void Main(){
		Console.WriteLine("Hello world");	//Don't forget the semicolon
	}
}

Standard input, standard output, standard error output

Use the methods in System.Console

//Standard input
System.Console.ReadLine()  //Read as a String type
//Use int's Parse method to convert to a number
int.Parse(System.Console.ReadLine())

//Standard output
System.Console.WriteLine(/*Output contents*/);  //Insert line feed code at the end
System.Console.Write(/*Output contents*/);      //Do not insert line feed code at the end

//Standard error output
System.Console.Error.WriteLine(/*Output contents*/);

//Can be described from Console onwards by declaring the use of System at the beginning of the code
using System;
Console.WriteLine("~~");

variable

//Declaration: Declare with data type
string variable name=value(String);
int variable name=value(Numerical value);
var variable name=value;	      //If you declare it with var, the type is automatically determined according to the value.

//Combine variables and strings
System.Console.WriteLine(variable+ "String");

Array

//Declaration and initialization
Type[]Array name= new Type[Element count];    //Overwrite existing array(reset)Can also be used
string[]Array name= {element, element};		//Array to store strings
int[]Array name= {element, element};		//Array to store numbers

//Add element
Array name[index] =value;

//take out
Console.WriteLine(Array name[index]);

//Output by separating elements
Console.WriteLine(string.Join(",",Array name));
// =>element,element,element

//Element count
Array name.Length

Multidimensional array

//Declaration and initialization
string[] array1 = {"bar", "foo"};
string[] array2 = {"var", "hoo"};
stying[][] array3 = {array1, array2};

//Define directly
string[][] array4 = {
	new string[] {"bar", "foo"},
	new string[] {"var", "hoo"}
};

//Define a multidimensional array using the new operator
//6x5 2D array
int[][] array5 = new int[5][];
for (int i = 0; i < array5.Length; i++) {
	array5[i] = new int[6];
}

Collection

//Introduction
using System.Collections.Generic;
//Generic =>Class that specifies the data type when declaring

List class

Unlike arrays, there is no need to set an upper limit on the number of elements at the time of declaration

//Declaration
var List name= new List<Type>();

//Add element
List name.Add(element);				//Add to the end
List name.Insert(index,element);	//Add to specified location

//Delete element
List name.Remove(element);

//Element count
List name.Count;

Divide the string and arrange it

String.Split(Split character);

//Assign to array
string[] = array = data.Split(',');

Dictionary

Create

using System.Collections.Generic;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var Dictionary name= new Dictionary<key type,type of value>();

Add element

Dictionary name.Add(key, value);

Get element

Dictionary name[key];

Element count

Dictionary name.Count;

update value

Dictionary name[key] =value;

Delete element

Dictionary name.Remove(key);

Loop processing

//Use KeyValuePair structure
foreach (KeyValuePair<string, string>Variable in Dictionary name{
	Console.WriteLine(variable.Key);
	Console.WriteLine(variable.Valu);
}

//Can be var
foreach (var variable in dictionary name) {
processing
}

random

Get a random number using the Random class

var random = new Random();
var number = random.Next()

Next method

Randomly generate a number greater than or equal to 0
The specification of the range of numbers generated by the Next method is as follows

var random = new Random();
var number = random.Next(1, 101);	//1 or more and less than 101
var number = random.Next(10); //0 or more and less than 10

Conditional branch

if statement

syntax

if (Conditional expression) {
processing;
} else if {
processing;
} else {
processing;
}

DateTime structure

https://docs.microsoft.com/ja-jp/dotnet/api/system.datetime?redirectedfrom=MSDN&view=netcore-3.1

var today = DateTime.Today;	//today
Console.WriteLine(today);
// => mm/d/yyyy 12:00:00 AM
Console.WriteLine(today.Year);	//Today's year
// => yyyy
Console.WriteLine(today.Month);	//Today's month
// => m
Console.WriteLine(today.Day);	//Today's day
// => d

Iterative processing

while

var i = 0;			//Counter variable
while (i <= x);	{	//Repeating conditions
processing;
	i++;			//Counter variable increment
}

for

for (Counter initialization;Repeating conditions;Counter update){
processing;
}

for (i = 0; i < x; i++) {
processing;
}

//Counters can be declared even before for
int i;
for (i = 0; i < x; i++) {
processing;
}

foreach

string[]Array name= {element, element};
foreach(string variable in array name) {
Repeated processing
}

Method

Definition

//Method is defined in class
public class Methods {
	public static void Method1() {
processing
	}
}

call

public class Methods {
	public static void Main() {		//Main method is C#Is automatically called first when the program is executed
		Method1();
	}
	public static void Method1() {
processing
	}
}

argument

When setting the arguments, also specify the data type

public static void Method1 (int a, string str) {
	Console.WriteLine(a);
	Console.WriteLine(str);
}

Default value

public static void Method1 (int a, string str = "foo") {
	Console.WriteLine(a);
	Console.WriteLine(str);
}
//Arguments with default values are defined after arguments without default values

Named argument (label)

public static void Main() {
	Method1(str: var, a: "hoo");
	Method1(str: var);
}

public static void Method1 (string a = "bar", string str = "foo") {
	Console.WriteLine(a);
	Console.WriteLine(str);
	Console.WriteLine();
}
//Execution result
//hoo
//bar
//
//bar
//var

Variadic argument

public static void Method(params string[] lines) {
	//All arguments specified at the time of calling are arrays`lines`Will be added to and processed
	foreach (string line in lines) {
		Console.WriteLine(line);
	}
}

Return value

When setting the return value, specify the data type

public static int Method(int a, int b) {
	return x + y;
}

scope

Variable scope

The scope of a normal variable (local variable) defined in a method is in the method

public class Program {
	public static void Main() {
		int a = 3;
		Console.WriteLine(a);
		Method1();
		Console.WriteLine(a);
	}
	public static void Method1() {
		int a = 30;
		Console.WriteLine(a);
	}
}
//Execution result
//3
//30
//3

The scope of variables declared inside a block is inside the block

(The part surrounded by block => {})

public static void Main(){
	num = 6;
	if (num % 2 == 0) {
		string message = "Even number";
		Console.WriteLine(message):
	}
	Console.WriteLine(message);	//This gives an error
}

LINQ
LINQ makes it easy to process a collection of data

Introduction

using System.Linq;

Maximum value

・ First ask
Using LINQ’s Max and Min methods, the maximum and first values of the numbers in the array can be found.

using System;
using System.Linq;
public class Program{
    public static void Main() {
        int[] nums = {11, 46, 27};
        Console.WriteLine(nums.Max());
        Console.WriteLine(nums.Min());
    }
}
//Execution result
//46
//11

class

Class definition

public class class name{
}

variable

public class class name{
private string variable name;				//field
	
public class name(string variable name) {		//constructor
		this.Variable name=Variable name;
	}
}

field

Variables defined in the class
The value is retained as long as the object exists

constructor

A method whose name is the same as the type’s name (class name)
Method called to create an object from a class

Initialize the field by passing a value to the constructor when creating the object

var variable name=new class name(Value to pass to the constructor);

Access modifier

public => Can be called from anywhere in the program
private => can only be called in the defined class
internal => Can be called from the same project (any code in the same assembly)
Other,

  • protected
  • protected internal
  • private protected

and so on

Omission of access modifier

If you omit the access modifier of what is defined in the class, it will be treated as private.
If you omit the access modifier of the class itself, it will be treated as internal.

static
Variables and methods with static can be used in common for all objects
Can be accessed without creating an object

Property

Functions used when reading, writing, and calculating private fields
Private fields cannot be accessed from outside the class, so you need public methods and properties to access them.

public static int Num {
	get {				//Read
		return num;
	}
	private set {			//Prevent rewriting outside the class by making the setter private
		num = value;		//writing
	}
}

//Omitted description
public static int Num {get; private set;}

Class inheritance

Base class => Derived class
Inherited class methods and variables can be used

class Derived class name:Base class name{
public derived class name(Type derived class constructor) : base(Base class constructor) {
	}
}

Method override

class Class1 {
public string Value {get; private set;}

public Object (string value) {
	Value = value;
}

public virtual void Method1 () {// Make the base class method a virtual method
processing
]
}

class Class2 : Class1 {
public Class2(string value) : base(value) {
}

public override void Method1() {  Overridden processing
} } ```

##Method overload
Distinguish methods with the same name by the number of arguments and the type of arguments
=>Processing can be divided by the difference in arguments

#Namespace
A group that manages multiple classes

##Namespace example in standard library

System

Commonly used classes

-Arrat class
-Console class
-Exception class
-Math class
-Random class

Such

System.IO

Classes related to data and file input / output, etc.

-File class
-FileiInfo class
-FileStream class
-Directory class
-Path class

Such

##Call from namespace

 Namespace.Class.Method ();

 System.Console.WriteLine (string);

 using System; // If you specify the namespace with using, you can omit the namespace in the following description.

#Exception handling(Exception)

C#Program execution procedure

1.compile
-Convert to executable format
-Compile error:Spelling mistakes, grammatical mistakes
2.Execute
-Perform calculations and processing in sequence
-Run-time error:Cannot calculate, no file

Write exception handling to handle 2 run-time errors

##Exception handling function

  • try
    -Specify code in advance to detect processing problems when executing a program
  • catch
    -Describe how to respond when a problem is detected
  • throws
    -If no correspondence is described, leave the correspondence to the method caller.

###An example of an exception
-Divide by 0

  • DivideByZeroException
    -Specify a non-numeric character string in numeric conversion
  • FormatException
    -Illegal null is passed as an argument
  • ArgumentNullException
    -Out-of-range access of the array
  • IndexOutOfRangeException
    -File does not exist

If exception handling is not described`Unhandled Exception’error occurs and is forcibly terminated when it occurs

##Exception handling description

try {
 The code you want to detect the exception
}
 catch (Exception e) {// Exception handler e is an Exceprion object that contains detailed information about the exception.
 Processing when an exception occurs
 //例)
 Console.WriteLine (e.Message); // Get a message explaining the exception
 //例外に関するメッセージを標準出力ではなく、標準エラー出力に出力する
	Console.Error.WriteLine(e);
}
finally {
 Processing to be executed after all exception handling is completed
}

 //特定の例外を補足する
 catch (exception e) {
 processing
}
 //例)
catch (DivideByZeroException e){
 Console.Error.WriteLine (Cannot divide by 0);
}

##Catch multiple exceptions
Write an exception handler for each exception

 catch (exception 1 e) {
 Exception handling
}
 catch (exception 2 e) {
 Exception handling
}

Note that if you write the handler of Exception which is the base class before the handler of individual exception which is the derived class, a compile error will occur.

##Intentionally throw an exception
You can check if exception handling works normally

try {
 Code for exception catching
 throw new exception class (detailed message of exception object); // message is optional
}
 catch (exception class e) {
 Exception handling
}

##Exceptions to the caller
Exceptions that occur in the called method etc. are transmitted to the caller and handled.

 //呼び出されたメソッド内の例外ハンドラから呼び出し元に再度例外を投げる(例外の再throw)
catch (Exception e) {
 Exception handling
	throw;
}
 //投げられた例外は呼び出し元の例外ハンドラで例外処理される

##Exception class structure

Exception
	|—SystemException
		|—FormatException
		|—IndexOutOfRangeException
		|—ArithmeticException
			|—DivideByZeroException
		|—ArgumentException
			|—ArgumentNullException

Exception of derived class can be caught by base class above itself

Tags:

Updated: