CategoryBegginer

Boxing and unboxing

Boxing and unboxing are processes of converting value types to object type or from object type to a value type. During boxing value type is taken and converted to object type, while during unboxing object type is converted to explicitly defined type, so we can say that Boxing is implicit and unboxing is explicit.

Let’s look at boxing through example:

We have a job to convert two numbers to an object type. Usually we assign numbers to an integer type. Int type can hold numeric values from -2,147,483,648 to 2,147,483,647, but Int64 can hold larger numeric values from -9223372036854775808 to 9223372036854775807. So our job is to convert numbers 2,147,483,000 and 3,147,483,800 to an object. We can do it simply by writing following code:

What we essential did was that we created two variables one int variable to hold number 2147483000 and Int64 variable because number is to large to be stored inside int variable. Then we took those two variables and assigned them to an object type variables.

Unboxing is an opposite process of boxing. First we will take a few object variables with different types of values, like string, int and double and convert them to a desired type by casting. Casting is specifying type in round brackets before objects variable. Let’s take a look:

There are a few things you should always consider while boxing or unboxing.

  • Both boxing and unboxing are expensive operations. While boxing a new object must be created on a managed heap. While unboxing does not usually require creating allocation of a new memory it is still a expensive operation.
  • You can unbox object to a lot of different value types. For example, you can unbox numeric value 5 to a int or a string if you wish:

  • List of objects is also possible

  • Beware of InvalidCastException exceptions that occur when unboxing incorectly

Using keyword

Before we continue to FileInfo and Streams we need to explain using keyword in details.

Using directive

Using directive shortens our syntax so that we do not always have to type entire namespace:

Using directive grants us access to static members having to qualify the access with the type name:

Using directive enables us to create alias directive.

Using statement

Using statement provides us with a easy to use syntax which in return guarantees us with that types that implement IDisposable interface will be disposed of when we finish with them. For now do not stress yourself with questions like why do I need to dispose of something and what use IDisposable interface is to me. Those questions will be covered in a future post.

Example of using statement

Usage of using statement is straight-forward.

First we type using keyword and open parentheses, and inside of those brackets we instantiate class that implements IDisposable interface.  After that we proceed to use class instance inside curly brackets.

Of-course  you can instantiate more than one class while using using directive, just remember to separate them with coma:

I hope you will find using keyword helpful. I certainly use it on a daily basis in both forms

File and FileInfo

While trying to copy, move, rename, create, open, delete and appending to files we use File and FileInfo classes. File and File info classes derive from System.IO namespace. File class provides us static methods to work with files and FileInfo provides us with instance methods. Generally, you will use File class when working with a file and perform one operation on it. Difference between File and FileInfo approaches is that FileInfo does security checking only once (while accessing files).  Because FileInfo is a instance method it does not tack changes to a file so you will have to take a lot of precautions while using that class. File class is on a disadvantage, because you always have to apply path to a file, meaning, it takes more parameters than FileInfo class. Try discovering yourself which approach is faster in your scenario. Also both classes help us while creating FileStream (to be explained in next post).

Common operations working with File class

 

Common operations working with FileInfo  class

 

I hope you had no problem with learning how to use File and FileInfo classes. If you found File and FileInfo classes interesting I recommend that you continue learning about Streams.

Arrays

Arrays are zero based, fixed size collection of elements, meaning first index of an Array is 0, and once we initialize an array it’s size cannot be changed. Array is an reference type. System.Array class holds static and instance methods that we can use with arrays.

 

Declaration

Arrays can can contain reference or value types. We declare an Array with type followed by [] (square brackets) and variable:

 

Initialization

As Arrays are an reference type we initialize it by assigning Array variable to Array instance but instead of using round brackets after instance type we use square brackets which should hold integer value. That value is specifying size of our Array and that value cannot be changed. If input number 3 inside square brackets, first index will be 0 and last will be 2. We can also use var keyword while initializing an Array.

 

 

Populating an array with values

 

Example shows array of city names that can hold 3 elements and multiple approaches to populating an array with values:

 

 

How to use arrays

Retrieve value

We retrieve an element from array by specifying index of that value. If for example we wanted to retrieve first element from our previous array we can access that value like this:

 

Approach 1 is commonly known as manual initializer, and Approaches 2 and 3 are known as collection initializers.

Iterate through array

We can iterate an arrays using for and foreach statements

 

 

Find index of an value

Change value of an element

Detect if array holdes speciffic value

Lenght of an array

 

FAQ:

Q:What will happen if we try to add more element to an array than array can hold?

A: Compiler warning will be received.

 

Q:What will happen if we try to add less element to an array than array can hold?

A: Not populated elements will be null.

 

 

Q: What will happen if we try access element of an array that is out of scope of an array?

A: IndexOutOfRangeException will occur.

 

Q: What will happen if we try to find index value of an element if that element does not exist inside of an array?

A: You will get value -1.

 

Good practices for using arrays:

Use plural variable name. Variable name cityNames is better naming convention than cityName.

Use arrays only if you know array size during design time because array size cannot be changed during runtime.

Populate your arrays with collection initializer technique because they are less error prone and easier to read.

Code Snippets

Code snippets are convenient way to save time wile writing code. By typing just a few easy to remember keywords you will save a lot of time and implement desired outcome successfully.

By typing following keywords and pressing tab following outcomes will appear. Beware, keywords are case sensitive.

 

class + Tab will create class

 

enum + Tab will create enum

 

 

ctor + Tab will create constructor

 

 

propfull + Tab + string + field+ Tab + Property will create property

 

 

prop + Tab + int + Tab + AutoImpelemntedPropertyName will create auto implemented property

 

 

svm + Tab (Useful for your Console program, but remember only one is Main method is allowed)

 

 

foreach + Tab + dataTypeName + item + collectionName will create foreach loop

 

 

 

try + Tab will create try-catch block

 

 

tryf + Tab will create try-catch block

 

 

 

Constructor

Constructors are a public methods with the same name as a class were they resides. Constructors are always created with a class, weather we write it ourselves or if class creates it for us(although it will not be visible ). Role of constructors is to initialize fields when we instantiate class. It is possible to create multiple constructors. Adding „: this()“ after parameters of constructor with parameters will execute default constructor before constructors with parameters. To easily create constructors type ctor keyword an new one will be generated for you.

 

If you have ever initialized class you have consumed constructors in one way or another. Example of consuming constructors would be in previous example where we have instantiated ClassWithConstructor class with string “Mike” and integer 1.

 

Is it possible to forbid class to initialize constructor?

Yes it is, just create empty one and set private access modifier.

 

What about other access modifiers? Can I use them all?

Public, private, protected, internal, or protected internal access modifiers are allowed to be used with constructors.

 

How can i initialize base class constructors ?

Simply type

after constructors parameters . Remember, you don’t have to supply parameters for base class constructor  because base constructor will always be called before derived class constructor, weather we call it or not.

Explicit Interface member implementations

Explicit Interface are implemented explicitly if for example two or more of our interfaces implement same method/properties/etc… names and different implementation. Other usages can be to implement strong typing and cleaner code.

 

 

Implicit Interface member implementations

Example will show how to create new interface called ICarSpecifications which will hold a property and a method. ICarSpecifications interface will be implemented inside Car class and its implementation will be inside region InterfaceImplementation(note: you can manually create implementation OR when you type ICarSpecifications pres keys CTRL + . and click Implement missing members. Region will not be implemented automatically).

 

Tomorrow we will continue with explicit interfaces implementations.

Interfaces

Interfaces are a type of contract between interface and class or struct. Interface is defined by interface keyword and the name of interface should usually start with capital letter I to make it more recognizable.

 

When we say Interface is a contract, what do you really mean?

Every class or struct that uses some interface must implement all of its functionalities.
Why would you use Interface at all?

There are multiple reasons actually:

Firstly, a class or classes that use Interface must use all of Interfaces functionalities. Secondly, names of all properties, methods… must be same in all classes as they are in that specific Interface. Furthermore Interfaces are obligatory, imagine situation where you must in a few classes use 3 methods Get, Insert and Delete, when you use interface with your classes there is no possibility of forgetting to implement either of these methods. Lastly, because C# does not allow us to inherit multiple classes but allows us to implement multiple Interfaces, we can create multiple interfaces where each interface inherits a class and use these interface as workaround.

 

What can we define inside Interface?

Events

Indexers

Methods (but without implementation)

Properties

 

What are Interface limitations?

Interfaces cannot define:

Constants

Constructors

Fields

Operators

We cannot make interface or its members static

 

What about access modifiers?

By default all interface members are public and we cannot change it.

 

Can we instantiate Interface? Yes we can, limitation is that you must instantiate them using a class or struct that implements that interface.

 

Is there a limit to how many Interfaces can we implement at the same time? Yes and no. Although language specification state that you can implement as many Interfaces as you like, there are few technical limitations: heap size and metadata tables size, but worry not, you will never exceed that limit.

 

Please, drop by tomorrow to see a few Interface examples .

Explicit Interface member implementations

Implicit Interface member implementations

 

 

 

 

 

Inheritance

Inheritance

What exactly is Inheritance? MSDN explanation says : Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive. If ClassC is derived from ClassB, and ClassB is derived from ClassA, ClassC inherits the members declared in ClassB and ClassA.

So what can we inherit? For example we have Car and Motorcycle classes, and as we know cars and motorcycles have a few things in common such as engine and color. We could create a base class named Vehicle that has those properties and make Car and Motorcycle classes which will inherit Vehicle class.

 

Can i inherit from multiple classes? No, but you can Inherit multiple Interfaces that inherit one class.

 

I don’t wish for my class or method to be directly instantiated. What can I do about that problem? You can make those classes or methods abstract. Beware, when you make your class abstract one, none of your class members have to be marked as abstract, but if at least one of your members is marked as abstract, entire class must be marked as abstract.

 

Can derived class access private fields of base class? No, it can not. You can only access internal, public, protected, and protected internal members of a base class.

 

Is it possible to prevent our class from becoming other classes base class? Yes, mark that class as sealed and other classes cannot inherit from this class.

© 2019 LearnC#WithDarko

Theme by Anders NorenUp ↑