C# Basic File and Directory

C# Basic File and Directory

So most people know that you can store information on your computer, things like documents, games, etc. When making a program you can tell the program to find certain files, use the information in those files,  and copy, delete or move them. You can also have the program write or read text files and create keys to the registry system. 

Most of those things are done through the System.IO Namespace

The classes in this namespace for accessing a file system are:

Generally the difference between the ones with info in the name are that they have properties and instance methods. While the one without info has static methods. So the info ones are generally more efficient when doing multiple actions with the same file, because the without info class always does a security check, which isn’t always necessary, and most methods require the path to the file.

If you want to do multiple actions on multiple folders you should use the Directory or DirectoryInfo classes. Specifically the GetFiles or EnumerateFiles methods.

  • The links should be to the articles on the Microsoft programming guide on the specific class or namespace.
C# key words

C# key words

Key words are predefined reserved words that you can’t use for things like variable names unless they have a @ prefix. (so @int could be a variable name but int can’t.) There are also contextual keywords that are only predefined in certain contexts so you can use them as identifiers if you want. For example orderby is only predefined when its used in a query as a clause.

There are about 77 key words(not including contextual ones) so I will be breaking them into categories.

The first category of key words are types, so these would be words used to say that this variable is a number or its a word.

1.char: is typically a single letter, or number of some kind, which is a Unicode UTF-16 character, and its a reference type

2.decimal: is a floating type numeric value so it can be any number from ±1.0 x 10^28 to ±7.9228 x 10^28, its generally for really precise numbers because it can go to 28-29 digits(after the decimal point I think) and its a value type

3.double: is a floating type numeric value so it can be any number from ±5.0 × 10−324 to ±1.7 × 10308 , its typically the one I use when coding, and it has the ability to go to 15 to 17 digits(after the decimal point I think) and its a value type

4.int:is a integer number so it can’t represent any kind of decimal, its range is -2,147,483,648 to 2,147,483,647 and its a value type

5.sbyte: is also for integer numbers and its range is -128 to 127 and its a value type

6.float:is a floating type numeric value so it can be any number from ±1.5 x 10−45 to ±3.4 x 1038 and it can have 6 to 9 digits(after the decimal point I think) and its a value type

7.object: this can be whatever, its basically the super class of all the reference type

8.bool: is a structure type and can only be true or false, this is generally the output of a if statement, if the statement is true it runs the code blocked by the if statement if false it doesn’t. The default for bool is false.

True and false are keywords and are the output of a bool.

9.short:is also for integer numbers and its range is -32,768 to 32,767 and its a value type

10.string : is a sequence of zero or more Unicode characters and its a reference type.

11.uint: is also for integer numbers and its range is 0 to 4,294,967,295 and its a value type

12.ushort :is also for integer numbers and its range is 0 to 65,535 and its a value type

13.byte: is also for integer numbers and its range is 0 to 255 and its a value type

14.long: is also for integer numbers and its range is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 and its a value type

15.ulong : is also for integer numbers and its range is 0 to 18,446,744,073,709,551,615 and its a value type

16.struct: is a value type that encapsulates data and is generally related to functionality.

The next category is modifiers:(coming later)

C# Arrays- useful methods(no examples)

C# Arrays- useful methods(no examples)

Properties

So properties are used like : arrayName.propertyName

The Rank property will tell you how many dimensions the array has.

The Length property will tell you how many elements are in a array.

Methods

The copy() method creates a copy of the array. The copy is shallow this means that it copies all the elements of the array whether its a reference type or a value type. However, it doesn’t create copies of objects it just copies the reference to that object. (a deep copy would create a copy of that object so the original and the copy would not be referencing the same object)

The Clear(Array array , int index, int length) method will turn the array starting from the index for length elements. So if you put 2 for index and 5 for length, it will set from index 2 to index 6 to the default for their type.

The GetLength(int dimension) method will return the length of the dimension you gave it. So say you are using a three dimensional array and you put a 2 for the parameter, it will give you the length of the third dimension. (it counts dimensions starting from 0 so for a single dimension array you would only be able to find the length of the 0 dimension without a error)

The GetType() method will return the type of a object it is, so if its a int it will return int if its a long it will return long, if the array is of a class you made it will return that classes name.( to clarify the full method is Object.GetType() not Array.GetType(), although a array is technically a object)

The GetValue(…) method has eight different version. Although there are really only 4 kinds, they just specify the indexes of 32 bit integer (Int32 or int) or 64 bit integer (Int64 or long). So I’ll be using int but each instance of the method could have long as the type for all the parameters.(Note: all parameters must be int or long you cant mix and match them within the same method). Also keep in mind that indexes start from zero in a array.

  1. So GetValue( int index1) is for use with single dimension arrays and will give you the value of the element at that index.
  2. GetValue( int index1 , int index2) is for two-dimensional arrays, and will give you the value of a array at index1 in the first dimension and index2 in the second dimension.
  3. GetValue( int index1, int index2, int index3) is for three dimensional arrays.
  4. GetValue(int[] indices) is for multi-dimensioanl arrays, the number of elements in indices should be equal to the number of dimensional the array you are trying to get a value from with element 0 being the index in the first dimension. (I am assuming)

The SetValue( Object value . . ) method basically the same as GetValue but you are setting the values at those indices, so you also need the value parameter which will be the first one.

The IndexOf( . . .) method has 6 different versions. I will be covering three because the other three just seem to be slightly different versions of these three. Also this only works for one dimensional arrays.

  1. IndexOf(Array array, object value) will return the first index that value appears in the array as a int. Everything is a object so don’t worry about the type.
  2. IndexOf (Array array, object value, int startIndex) will return the first index of the value starting from startIndex in the array as a int.
  3. IndexOf (Array array, object value, int startIndex, int count) will return the first index of the value from between startIndex and startIndex+count-1. So if start index is 2 and count is 5 it will be from between indices of 2 and 6.

The LastIndexOf( . . .) method is the same as IndexOf but its just the last index that the value appears at rather than the first.

The Sort( . . . ) method has 17 different version 9 look very similar to the other 8. Of which I will only be going over two because all the others involve a IComparer parameter which I believe is just something telling the method specifically how you want it sorted or it wants you to use another array as a key for the one your sorting.

  1. Sort (Array array, int index, int length) will rearrange the elements from index for length. So say index is 2 length is five the elements from 2 to 6 will be rearranged according to the default, which I believe would be something like alphabetical for strings.(so like if the array was the alphabet the first element would be “A”.
  2. Sort(Array array) will rearrange the entire array according to the default IComparer.
C# Jagged Arrays

C# Jagged Arrays

So, a Jagged array is basically a array of arrays. This means that the elements in a jagged array are single-dimensional or multi-dimensional arrays. You initiate a jagged array by doing:

type[ ][ ] nameOfArray = new int[#][ ];

-or in the case of the elements being multidemnsional arrays-

type[ ][ , ] nameOfArray = new int[#][ , ];

The number is optional(# can be a symbol for number). It’s just telling the compiler how many elements are in the jagged array, and c# doesn’t require you to tell it that when you initialize the array.

You put elements into the array by:

nameOfArray[indexNumberOfElement] = new type[#];

-or multi dimensional-

nameOfArray[indexNumberOfElement] = new type[#,#];

-or with the arrays being specified-

nameOfArray[indexNumberOfElement] = new type[#] { Var1, Var2,etc};

You can also declare and initialize at the same time:

type[ ][ , ] nameOfArray = new int[#][ , ]

{

new type[#,#] { {Var1,Var2,etc} ,{Var3,Var4,etc}, etc},

new type[#,#]{ {Var1,Var2,etc} ,{Var3,Var4,etc}, etc},

etc

}

For the jagged arrays the number of elements in the array elements can vary, as in a array of 4 elements and a array of 20 elements can be in the same jagged array. You can also leave out the “new int[#][ , ]” and it will still compile.

Microsoft doc link

C# arrays – basic information

C# arrays – basic information

An array is a place you store multiple variables of the same datatype. There are three types of arrays single-dimensional, multi-dimensional and jagged.

The single and multi arrays are what they sound like with the single dimensional array acting like a row, while the multi is like a grid, or a cube. So the single array is made like so:

type[ ] arrayName = new type[numberOfValuesBeingPutInArray];

or

type[] arrayName = {value1, Value2, Value3,etc};

You can also make a array by by doing:

type[] arrayName = newType[] {{value1, Value2, Value3,etc};

The multi-dimensional array is very similiar as it essentially just changes the [] to [ , ] or however many commas like so:

type[ , ] arrayName = new type[ numberOfRows, numberOfColumns ];

type[ , , ] arrayName = new type[ numberDimension1, numberDimension2, numberDimension3 ];

type[ , ] arrayName = {{V1,V2,etc}, {V1,V2, etc} , etc};

type[ , ] arrayName = {{{V1,V2,etc}, {V1,V2, etc} , etc}}, {{V1,V2,etc}, {V1,V2, etc} , etc} , etc} ;

You can essentially have as many dimensions as you want so long as you have the memory space for it and your compiler can handle it. If you declare an array without initializing it(assigning it values either with new or the {}, you would need to use the new operator to assign the values similar to what’s shown in the third example for single arrays.

You cannot change the length or number of dimensions after the instance of the array is made. If you don’t declare what the values in the array are they are the default for the type( 0 or null). The elements can be of any type so long as they are within the type of the array. This means that if you make the type Object (as in the object class that all types should be a part of) you can put whatever value want in it, but if you make an int array you can only put ints not anything else. When calling from an array the first value is at zero and the last value is at the number of values-1. So, arrayName[0,0] would call the value in the first column and the first row.

For example:

int array[] = {1,2,3,4,5};

System.Console.WriteLine(array[0]);

// the console will print out 1

System.Console.WriteLine(array[4]);

// the console will output 5

You can use a foreach loop to go through an array, which will be discussed in a different post. Along with some common and useful methods used with arrays.

A jagged array is an array of arrays , and this is the link to the more detailed post on them.

The Microsoft tutorial for this is here.

C# constructors

C# constructors

A constructor is what creates the instance of a class(also known as a object). They essentially define the default values for a object, even if you don’t specifically make a constructor you will still have the parameter-less constructor, which is essentially the default that every class will automatically have. It will set all global variables that aren’t defined to the default definition of their type.

A constructor is made by doing:

accessmodifier variabletype variableName;

accessmodifier variabletype2 variableName2;

public ClassName(parametertype1 parameterName, parametertype2 ParameterName2)

{

variableName = parameterName;

variableName2 = parameterName2;

}

It’s easiest to think of a constructor as a kind of method where it is used to define a object( aka giving values to global variables for that instance of the class), and it being the same name as the name of its type( with it’s type being the class you are making a instance of).

There are also static constructors which basically defines the static global variables.

So something like:

accessmodifier static variabletype variableName;

static ClassName()

{

variableName = value;

}

Notice that the static constructor is parameter-less since, the static variables shouldn’t be changing in the code based on which instance is being used.

You call a constructor by creating a object of that type with the correct arameters, in other words like this:

ClassName objectName = new ClassName( valueForParameter, valueForParameter2);

The valueForParameter can of course be a variableName or a value(as in say the parameter type was int you could but 12 or 15 or you could put the int variable myInt that you have already assigned a value).

There is more information on the Microsoft docs guide.

C# interfaces

C# interfaces

Note: I have only ever actually used interfaces in java, mostly because I don’t see a need for interfaces when making programs to be used in Unity.

A interface is essentially a completely abstract class. This means all the methods should be abstract. So its a group of related code that a non-abstract class or a struct need to implement. They are used because a class can only inherit one class but it can inherit multiple interfaces, and struct can’t inherit.

You declare a interface by:

interface IInterfaceName<T>

{

returnType MethodName( parameterType1 parameter1);

}

So you use interface instead of class and the name of the Interface should have a Uppercase I at the very beginning. Between the brackets is a abstract method.

You have a class inherit a interface by:

public class ClassName : IInterfaceName<ClassName>

{

}

The class that is implementing the interface must be public, non-static and have the same name as the interface member(the thing between the <>). It must also define all the abstract methods that don’t have a default. It has a default if you define the method in the interface(I believe you need to be working with c# 8.0 and above to do this though), but if you define the method in the class that default will be overridden. If the class that is implementing the interface is abstract it must still define the methods, but you can define them as abstract you just need to essentially tell the compiler that the method is abstract in the class. If a class were to inherit ClassName it would also inherit the interface, although you can still re-implement it. Classes can also define extra indexers and properties(so like get and set methods) for a property or index that is defined in a interface.

Click for info on this from Microsoft.

C# methods

C# methods

Methods are basically the places you put code so the program executes it. They are generally within a class and the main method of a class is where the program starts executing statements when running that code(unless another class is calling a method from that class). Generally the main method will call a constructor(link to a different post eventually) to make a object of that class, and/or call a different method to perform some sort of action.

The format for making a method is

accessmodifier optionalmodifier returntype MethodName( parametertype1 parameterName1, parametertype2, parameterName2)

{

//statements

}

The default access modifier is private, and putting it there is optional, so long as you want the access level to be private, if you want it to be public you have to put public. The optional modifiers i am talking about are things like abstract, sealed, static, ect which modify how you can use the the method. The return type is the datatype, or reference type you want your method to return to the place it was called from. If there isn’t a return type the keyword void should be in its place. The parameters are variables you are giving the method when you call it, if the method isn’t suppose to take any variables, leave the parenthesis empty.

When calling a method you have to pay attention to the return type if its a void method you need to call it something like:

object.MethodName( parameterName1 , parameterName2);

if it has a returntype it will need to be something like:

returntype variuableName = obj.MethodName(parameterName1, parameterName2);

The difference between the two is essentially that void is just performing a operation and shouldn’t be expected by the code to return something, while with a returntype the method does need somewhere to put the value it is returning.

The main method should be formatted along the lines of:

accessmodifier static void Main()

{

//statements

}

That is all the information I consider to be basic information there is of course more information at the Microsoft doc for c# methods.

C# variables

C# variables

In C# a variable is a name given to a space in the computers memory that the program manipulates. The various types of variables decides the size,layout and the range of values for that space, as well as the operators that can be applied to it.

These types are separated into value types and reference types.(built in means that the types should be available in any class )

  • Value types:
    • Simple types :
      • Signed integral(sbyte,short, int, long);
      • Unsigned integral(byte, ushort, uint, ulong);
      • Unicode characters (char);
      • IEEE binary floating-point( float, double);
      • High-precision decimal floating-point (decimal);
      • Boolean( bool) -true or false ;
    • User defined types :Enum types (enum E { . . . });Struct types (Struct S { . . .})
    • Nullable value types:Extensions of all other value types with a null value
  • Reference types
    • Class types
      • Ultimate base class of all other types: object
      • Unicode strings: string
      • User-defined types of the form class C { . . .}
    • Interface types
      • User-defined types interface I {. . . }
    • Array types
      • Single- and multi-dimensional
    • Delegate types
      • User-defined types of the form delegate int D( . . . )

The variables I tend to use are string, int, double, float, char bool and the reference types. You can also use the key word var to make a variable, it has to be within a method though.

You declare variables by doing:

variableType variableName = variable;

so when declaring an int it would be something like:

int myNum =5:

You don’t have to declare a variable and assign it a value at the same time so long as you assign the value before you use it.

In which case you do:

variableType variableName;

If you don’t want anyone to be able to change the variable after its declaration(and you do need to declare the variable for it to work). You put const in front of the variableType so it would be:

const myNum=5;

which would cause an error if someone tried to overwrite the variable assignment later in the code. If you are just changing the assigned value just do:

variableName = Variable;

You can declare multiple variables of the same type at the same time by doing:

variableType varN1=v1, varN2=v2, varN3 = v3;

Note you can’t use key words as names for variables, and you want the name to be somewhat descriptive so you know what it is when you use it. The names are also case sensitive and should start with a lowercase letter (although I don’t think the lowercase part is required by the system), they can’t contain whitespace and I believe they can only use letters,numbers and the underscore character( _ ).

C # classes

C # classes

Classes are a reference type. So they essentially tell the program that this set of constructors, methods, etc is associated with this object. So a class is really the blueprint for a object you are making, whether that object is in another class or is embedded in the class.

In C# there are namespaces which are essentially groups of classes. Most of these namespaces are for classes that the language gives such as System, which has the Console class in it. You can of course make one yourself. If you are using methods from a different class make sure to import it or have your class inherit it. I will talk more about this in a different post which I will link, If I remember.

So you use classes by creating a object that has that class as its type. For example:

Meclass whatever = new Meclass();

So it’s: NameOfClass NameOfObject = CallConstructore();

With the constructor call being new NameOfClass(VariableThatMatchesAConstructor)

You create a class by doing:

public class ClassName

{

//methods,constructors global variables, etc

}

So ‘public’ would be the access-modifier (will hopefully make a post on this too but for now you can look at Microsoft docs aka where I get most of my information on C#), the rest is fairy self explanatory.