It has been a buzz word for some intermediate level C# developers, ‘Dependency Injection’ is sometimes really hard to understand because we couldn’t understand the need for it.
In simple words, think about the scenario where you are developing an application which saves some data in a file and that file handling. You might code something like below initially
Here we are defining
- Which file to communicate (fileName)
- Where to access the file and (the file path which is appended in fileName)
- How to access it (other params of the fs object)
Then think about what if we suddenly think we are not going to write this on a File instead we are going for SQLite or some other options. So, it need a complete rewrite of this right. Its ideally something like “We are changing a lot of code in the client”. Here client is that who leverages the service from the file (or DB, in the new (future) scenario).
To handle this scenario there are two common practices.
- In client embed the logic of locating the service
- Tell the client about some dependency and make an external code which will help the client to find the service.
Both of these are more similar. Its like to achieve practice 1, one easier option is to use practice 2. So we call this as “Dependency Injection” and that extra code we call as “Dependency Injection Framework”. Things like Spring Framework and Hivemind dose the “Dependency Injection Framework” role. Scott Hanselman has a list of them for .NET.
IoC vs DI
IoC, Inversion of Control, people confuse this with Dependency Injection. But understand IoC is a generic team, meaning rather than having the application call the methods in a framework, the framework calls implementations provided by the application.
DI is a form of IoC, it is a solid term, where implementations are passed into an object through constructors/setters/service look-ups, which the object will ‘depend’ on in order to behave correctly.
Yeah each CPU architecture performs separate functions to perform same functionality. But just think about we are changing the CPUArchitecture to another in future.
This is a type of a Dependency Injection we call it as Constructor Injection. But this is clear enough to demonstrate the need of why we should inject the dependencies. Hope to meet you with another post with Advanced DI.
After this post, someone contacted me personally and said he is very impressed with this article personally this is the first time someone call or email me for one of my blog post it sounds great right. Last friday, it started in a perfect manner. I got up and got a notification in Viber, same close person from out side Sri Lanka sent me this
AA Isham I want a simple question on the same topic (types and casting) to determine his C# knowledge.
I replied him
Ask for the difference between a = a + b; and a += b;
Funny question right, because all the books and our teachers taught both of them are same. When we were beginners we wrote some code, that returned same results and after we grow up a bit we checked IL code, yeah thats also same like the below,
for both of the below,
so what the difference could be, and this seems a foolish question and answer should be “No differences” right? but you are wrong.
You want proof, okay open Visual Studio, make it two (shift + click on the VS icon on taskbar) make two console applications and write below on each of them
VS will tell the first one is buggy. Leave it and run the second one, it will run without any errors.
short + short = int
Because this is how C# designers see it. In C# size order for Integral types comes like
long and practically type
int can cover “most” calculations. Programmers rarely use
byte when it comes to complex arithmetic. I mean we don’t “practically see 10 short values are added and multiplied and divided and again assigned to short you know. You might argue, but its the “practical” truth and
add CIL instruction is optimized towards
int. 16 bit arithmetic are too slow. And yeah, arithmetic operations in
short are 16 bit ones. If you are interested on why this is slow, read this.
But still they gave option, that runs
a += b because there should be an option for adding at-least two
short or lesser types and add push it to a
short type variable right. So to cover this what they have done is, they added an additional
conv.i2 statement which does the job of casting the operation to
Int16. For the last code piece above I got the IL code like below
So, its something like,
a += b means
a = (short)(a + b);. Which makes your code size bit more than if you have used
int. Look at the above IL code also there, the code size is 13 but for the same code size if I have used
int it is 12 (look at the first IL code).
So in best practice, do think too small means too optimal really it will cost some other way you don’t know. Read C# specifications well. I mainly want this to who write code in Xamarin free subscription because they have an IL code limitation.
We all know and have experienced the importance we have for castings in C#. Its just essential if you want to build any system that takes inputs, process and give output. What a basic computer does is the same functionality right? so logically we need casting
EVERYWHERE in computing. Even you can argue, “I am a C# programmer, I write a console application that takes two integers, calculate their sum of it and print the output, so where I have to cast here?” my answer is “CLR does this”.
In simple and understandable words, “casts are basically explicit conversion”. In internal conversions we can pretty much ensure on three things
- No special syntax required
- They are type safe
- No data-loss
Normally we can take conversions from smaller to larger integral types and conversions from derived classes to base classes as good examples for this type of internal conversions. Explicit conversions, require a cast operator. We have to explicitly say the
compiler to forcefully convert the type. So there might be a very possible data-loss.
Honestly (Un)Boxing is a subset of casting. Boxing means CLI consider a value type as reference type (that involves copying the contents of that particular value type which is on stack to the heap and returning a
reference to the particular object). This lets a value type to be passed wherever a compatible reference type is expected and also this allows virtual method calls and some other features of reference types to be processed on the value type. Unboxing
is the reverse of this boxing operation (getting back a value type out of a boxed object). Casting is taking a type (say, System.Int32) and consider it as another type (say, System.Double). When you box something in C#, you are casting it to another type.
The difference is that it allocates additional memory as a new reference type is created.
is are used in C# to safely cast things. Since C# objects are polymorphic its possible that a base class type variable can hold a derived type so to access the derived type’s method, it is necessary to cast the
value back to the derived type. However this has a risk of
InvalidCastException. This is where
is comes to the play.
is is used to check the compatibility of two objects with a given type and returns
as can used only with reference type and will return
null if casting fails. basically
Think of the below code piece,
Simply you can argue, this is a confusing and a useless way since we are using
keyword we are not sure about if
BAT is a type of
MAMMAL and yet we are invoking a method. And even worse, this code piece can make a meaningful
InvalidCastException to a
NullReferenceException we all hate it. But why in some places they have mentioned this kind of a code piece? this is where code readability comes to mind. We know if we are using
as, we are sure about this object can be converted to that type but if it can’t we are happy to accept a
null. However as I said before
as can only be used with reference types, by using this style of coding, we can tell code reader that the code involves only reference or unboxing conversions, and furthermore, that BAT is not null.
is does almost the same but by stating
we can say it can be a derived type or from interface. So again using
in necessary places ensures code readability and sometimes. Still to use
typeof properly we have to use
GetType() can be used closely to work with
typeof there is a slight different.
typeof is used when you want to get the Type instance representing a specific type.
GetType() gives the runtime type of the object on which it is called, which may be different from the declared type. The below example make a clarification on it.
Always remember, GetType actually queries a specific assembly (at runtime) for a type that might be defined within the assembly (Similar to new Object().GetType()). typeof on the other hand is determined at compile time.
Using GetType() in some instances might lead us to a null related exception, since this function has been defined something like below
So when we call this, this will only check from the calling assembly and some few other system assemblies (probably System and mscorlib). It does not check every assembly. So the string parameter inside GetType() sometimes needed to be a fully-qualified assembly
name. Thus in performance, typeof() takes little time than GetType() to get executed. Consider the example below
This will return the following output
I hope this will make more sense when you try to understand the above scenario.
This artcle, I originally wrote for Technet. http://social.technet.microsoft.com/wiki/contents/articles/32293.c-casting-and-type-checking.aspx
Its was 2004, when I was started to study Pascal lang. I was a better code writer (remember, those days, we write code first on a book, then we re-write on a MS-DOS machine and compile it) and one day our instructor asked us to write a program to calculate average marks of the students. He didn’t mention, for how many students we are going to calculate the average. I don’t know how other wrote the code, though in that class only 3 were regular attendees, we never look in to others books, we thought it as a very very bad habit. So I write a for loop (I am in love with “for loop” since 2004 and “foreach” since 2011) that iterates some x times (say 10 times, I forgot the exact number that I used) and asked for marks and add it to a predefined variable and then divide the sum with x and print the answer. This was praised by instructor. I was a very beginner to programming and this approach was an excellent one for people like that. This might be the same way how you also have done when your early programming ages.
Now, suppose if someone comes to you and ask to do the same program for un-known number of people, you might use some data structures (List, Stacks, LinkedLists) to make this happen. But you know there is a better, memory saving approach to this. Thats what we call as Variable Parameters. This is a classic concept for most people don’t use this these days in favor of data structures. This is a kind of
polymorphism but still really efficient.
A simple example for this in C# might be
Just look at the method
avg, that has been implemented with
params keyword with
int this means, this tells that the method has the ability to take variable number of arguments with same data type (here
But be careful when you define a param method and be sure to make the param parameter is coming as the very last parameter
Some extra tips
Comparing to regular method invocations params methods are slower, while they are really useful when designing a library for other programmers to widely use. If you have complete control over all usages of the method, you may not need params because you can simply add the necessary overloads.
Lots of confusion among the people on who to vote. Specially in my Akkaraipattu because a well known politician is campaigning in a place where most people hate but still people want him. When I was thinking about this, I had an idea. Human make mistake but computers not. So what if let us give a chance to decide on whom to vote to the tiny chiped board that has x84 capabilities…
Delegates, a main question when it comes to C# interviews. When I faced the internship interview at IFS last October I was asked a question “What is a delegate” I said “It is a way to achieve thread safety”, actually I used delegates in my Imagine cup project in 2013 but when I faced that interviews, I really had a good clear concept of it. I said its thread safety because the reference material I read the day before the interview had many points on Delegates but due to my bad memory I could remember only that point even in that Imagine cup scenario really I used Delegate to avoid some code execution complexities.
Then the interviewer asked me ‘What do you mean by thread safety” so I explained it. Then again he asked me “OK, now how will you explain delegates to a newbie using the points you said”.. this is the moment I had a
In simple words, delegates are the callback functions in C#. (I really forgot this point that time)
So this JS pseudo code will explain what a callback function is,
If you can’t read that simple code, sorry this is not for you actually. So just close this browser tab.
Let me explain this,
delegate int CalcFunc(int a, int b); declare a delegate
CalcFunc that accepts two
int parameters and return another
int type variable.
CalcFunc someCalcFunc = new CalcFunc(SumFunc); instantiate the delegate
CalcFunk that calls a method we defined in Line 19, that is
SumFunc which SHOULD return the same return type and the same parameter types of the delegate
Console.WriteLine(someCalcFunc(5,6).ToString()); I just perform some operations with the delegate instance
Line 10, I change the reference of the
someCalcFunc delegate to another same return type method
ProdFunc, I don’t really need to make another instance of this delegate
CalcFunc for this purpose, simply
someCalcFunc = ProdFunc; works well.
and later I just perform some other operations.
I hope you will be able to catch it. Happy coding 🙂
Blogging after a long time actually, I was bit busy with last exams and migrating to Colombo, Sri Lanka. I have a good news for you guys that I have joined IFS, Sri Lanka as an undergraduate intern that valid from 11th March to 19th June. Here, at IFS, this has a tremendous work place setup and the people as well. Wow thats amazing and I praise god for writing my fate to be here 🙂
So today I have learnt something special, which I didn’t really used even I didn’t read in any books I used for reading on C#. That is CONSTRUCTOR CHAINING.
In simple words, Constructor chaining is calling a constructor from another constructor. The called constructor may reside in the same class of the caller constructor risiding constructor or its super class(In C# we call it as
base class). The main advantages of this is we are avoiding boilerplate code as we don’t have to repeat the same operations and even this can be used, if all fields of the class to be initialized.
Lets see a small code for this,
Here for the
Box class I have two overloaded constructors with different signatures, that are
Box(int len) in line 7 and
public Box(int h, int w, int l) in line 13. First lets have a look at the constructor in line 13, that initialize a box object with three user defined parameters,
l that are
length of the
Box class. But in the same box class I need an instance that to represent a cube, where
l are the eual values, so instead of writing another logic for that I can simply create another constructor that calls the constructor in line 13 and put single value to all the variables
l. Thats what I have done in line 7. So just notice the syntax.
Here since we chain the constructor in the same class
keyword is being used. So how to chain the constructor in the super class,
See line 4 where I have did something
public Cube(int l):base(l,l,l) in this line and this is where I chain the constructor from the base class.
Now in the
Box if I try to add another constructor (say I am adding the missing default constructor)
This will return a compile time (or say, typing time 😉 exception) in visual studio stating,
This is because I am using a non default constructor in the base class. Even, the below also won’t work
To overcome this defining the default constructor in the base class is always safe, as below
So remember to create constructors for the base classes whatever we needed in the child class. And stating default constructor gives the freedom to create any kind of constructor in the child class.
Happy coding 🙂
Twitter’s xAuth is an exciting option which is not available for web based applications but available for desktop and mobile apps that uses Twitter SDK where standard web OAuth flow or PIN-code out-of-band flow is not an option. xAuth access is restricted to approved applications and if your present/past/future app needs it, request if from here https://support.twitter.com/forms/platform. I was using this xAuth in 2012 when I was doing a good solution for blind people for Microsoft Imaginecup contest.
Ok, lets back to the topic, for Xamarin, we have Twitter4j component which is such awesome and very simple component to provide Twitter SDK capabilities. Once you add that component it open its official documentation, that is a small code implementation with access to twitter using a previously created twitter app’s
AccessToken Secret. Today I tried to port this code to use with an xAuth enabled app. The code is,
Lines 30-32 makes a twitter configuration with my twitter app’s
ConsumerSecret. After it in line 34 builds the above configuration and pass it to
IConfiguration interface. Line 40 is the place, that does the xAuth magic. Refer this code, if you get “The screen name / password combination seems to be invalid.” error, that mean’s your username-password combination is wrong or xAuth wasn’t enabled for your twitter app. I hope you enjoy this post.
Happy coding peeps 🙂
(never forget to check the quiz below and comment the answer, I might give some prices to a lucky winner, seriously)
Happy New Year to all. May this 2015 brings you a peaceful mind && make you strong, geeky and || or nerdy.
While I come through my twitter timeline today I noticed that the
Binary(2015) is a palindrome number, that is
11111011111 wow thats amazing right. So I wanted to create an app to find which years return palindrome binary numbers.
This is hope you enjoy this. Happy coding peeps 🙂
Happy New year again.
QUIZ : What is the next.next year to return a octal Palindrome number?
Deadline -> Answer is the deadline, until that the quiz is open.