C # basic

9 minute read

table of contents

–What is C #?

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

What is C

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


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

//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;


//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");


//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];


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

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(',');



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{

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


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


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

DateTime structure


var today = DateTime.Today;	//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


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


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

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

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


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



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


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


When setting the arguments, also specify the data type

public static void Method1 (int a, string str) {

Default value

public static void Method1 (int a, string str = "foo") {
//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") {
//Execution result

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) {

Return value

When setting the return value, specify the data type

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


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;
	public static void Method1() {
		int a = 30;
//Execution result

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);	//This gives an error

LINQ makes it easy to process a collection of data


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};
//Execution result


Class definition

public class class name{


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


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


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)

  • 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.

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


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

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

A group that manages multiple classes

##Namespace example in standard library


Commonly used classes

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



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

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


##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

-Convert to executable format
-Compile error:Spelling mistakes, grammatical mistakes
-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
finally {
 Processing to be executed after all exception handling is completed

 catch (exception e) {
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.

catch (Exception e) {
 Exception handling

##Exception class structure


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