jay's old blog

this blog will be deleted soon - please visit my new blog - https://thesanguinetechtrainer.com

Strings and Searching and Enumeration

Searching for a string within a search the most basic operation when working with strings. For that, .net has excellent facilities. 

Now that enumeration thing, we already discussed that in an earlier post, by way of the Enumerator interface. It goes without saying that string implements the enumerator interface and you can enumerate through it.  

For this blog post, things are pretty straight forward. So, I am going to ask you to go directly to our code repository to see how it works.  

And the code for string enumeration is here.


Follow me on twitter, facebook and instagram for more updates. Thanks!

Base and Derived Classes and Inheritance and Interfaces

If you are reached till this point (assuming that you follow the flow of our blog posts) then, you must know all the essential stuff. This is the post where everything falls in place and you truly begin to appreciate what the object oriented approach means, and the whole thing about allowing code reuse and yet keep things stable and steady.  

You already know that c sharp allows you to build a hierarchy of classes. One class may derive from another class, that class may in turn be derived into another class. So, you can 'chain' stuff, allowing you to reuse what you want, and create new stuff as required. I am using the word 'chain' but a more appropriate term would be loosely coupled.  

One way to look at a propely done class heirarchy is to think of them as folks who are in touch with each other, but aren't tightly bound. So, they have their freedom and they know their responsibilities. To ensure that this 'loosely coupled' thing happens, c sharp provides an additional feature called as Interfaces. 

Interface 

Interface is sort of like a class in that it contains methods, properties (fields are not allowed), events as well as indexers. The difference is that, the interface itself does not contain an implementation for these members and all of them are public by default.  

[Note : events and indexers are not something our blog posts have addressed so far] 

Whenever I think of an interface, I always imagine a bare bones skeleton being given to me. I am free to build around that skeleton anyway I want. However, the basic structure has been fixed and that itself cannot be altered.  

Since the interface itself does not contain implementation of its members, it is up to you to derive from the interface and define your type. To continue with the skeleton example, while designing the body around the skeleton, you may choose a slim build or a fat build. You may decide to give the skeleton red eyes or blue eyes. You may decide to make it bald or long, flully hair. You decide the implementation. The interface gives you the outline.  

Derived and Base Classes 

It's not just interfaces from which you can derive from. You can derive a new class from an existing class. Then, you can derive another class from that class. You can keep goin like this.  

Of course, inherting (don’t get this confused with interfaces because I definitely did) can be blocked if the requirement calls for it. You may choose to all your entire type to be inherited. You may choose to all some methods to be overriden in the derived class. As always, you are in control of what you do with your type definitions.  

As always, find the sample illustrating this at our repo. 

Afterthought 

About that skeleton analogy.  

After discussign with my mentor, I realized that the 'skeleton' example to describe inheritance may not be hundred percent correct. We took an example of a cat. If I were to give you a cat skeleton, it is very well possible to make a lion or a cheetah out of it. That's because, apart from their small size, cats that you find at your home and cats that you find in the jungle (at least until they go extinct) or at the zoo (where hopefully they are looked after well) are essentially the same.  

That means, an interface is like a skeleton, sure. However, the skeleton can also be modified to some extent. If you are planning to build a Lion out of our cat skeleto, then you will want to make the bones stronger/bigger/longer before you put flesh around it. If you were given a Lion skeleton, and buildign a house cat, you will make th bones smaller and shorter.  

What I am trying to say is, the interface or the skeleton makes you a 'promise' that you can use said skeleton to build some kind of cat. It could be a tiny house cat or a fast running cheetah or jungle ruling Lion. It could be any other cat that your crazy mind is thinking. You have that luxury/freedom. What you don’t have is the freedom is go out of the cat family. For instance, you cannot take the cat skeleton and expect to build a giraffe out of it. It won't work that way. 

The 'promise' I mentioned above translates to a 'contract' in the world of c sharp programming. Whenever you use a Interface (derive from it), it's a promise or a contract that, yes, what the Interface has agreed to give you, you can expect to be delivered in full. More importantly, you don’t have to worry about its implementation. 

Of course, this is one view and one analogy of how I look at interfaces. Over time, you will form your own opinions about this. 

Follow me on twitter, facebook and instagram for more updates. Thanks!

Standard Interfaces – IComparable, IEnumerable and IDisposable

.NET provides (and hence is available in c sharp) for a number of standard interfaces. As you build your projects, you will keep a lot of standard interfaces. Keeping with the 80/20 rule, you end up using some of them more than others.  

Of these, I would like to put a spotlight on three interfaces that are mighty useful.  

IComparable 

This interface is useful when you wish to compare stuff, in a list. Depending on what object you send, the interface method will return if said object is behind, at par or ahead of the linked object.  

This works when you are working with lists. You want to find out exactly where a given object is in comparison to another object in the same list. Imagine a long list of people (like that queue they would make you stand in your school days. Or, that queue at the ATM or the petrol station or at the office cafeteria). You randomly pick two individuals (same individual can be picked twice if you so feel it) from the queue, and you wish to find if the first person is behind, ahead or at the same spot in the queue.  

Since the interface works with 'object' type, you can use it a list of any type. That is what makes it neat. 

IEnumerable 

IEnumerable and IEnumerator interfaces give you access to every element in a collection. As always is the case with interfaces (or object oriented programming in general) you don’t really have to worry about the actual implementation of the collection.  

The IEnumerable connects to the collection, and you use the IEnumerator gives you some kind of cursor. Use the cursor (IEnumerator) in combination its collection (IEnumerable) to traverse through the collection happily.  

In addition to these things, you also use the 'yield' keyword. It only works in combination with iterators, which is where you use this particular interface. 

The thing about this interface is that allows you to build better looping systems. Normally, you would go with a for loop (with the index i, and i++ and all that).  However, with this, you can build more efficient looping systems that work really well with your custom types. Combine this with Generic types or object types and you have an implementation that provides you instant loops for almost any scenario. 

IDisposable 

You probably wont use this right now because we will revisit this whole thing when we are discussing memory management. Later, later.  

Check with our code repo which demonstrates this, and as usual has lot of comments to help you understand.

Follow me on twitter, facebook and instagram for more updates. Thanks!

Object Life Cycle – Garbage Collection and so many other stuff

This will be a long write up.  

One of the cool things about using a language like c sharp is memory management. In the old days, like in C programming age, you had direct control over where your data is stored. There are pointers that make this possible. For super cool developers, having that kind of control is awesome However, even super experts make mistakes and having that kind of control may not be a good idea. 

That is where the memory management of c sharp comes into play. In c sharp, there is something called as garbage collector. Think of the garbage collector as a librarian at the...library. You want a book. Instead of allowing you to pick up the book you want, the librarian will go and get the book for you. She won't let you go inside though. She believes that you will mess things up. However, she is fast and extremely good at her job. She will always get you the book you want, almost all the time. As long its in the library, you know she will get it for you.  

As a library goer, all you need to know is, if the library website says that a book is available, you can bet your expensive computer that she will get it for you. The garbage collector is like that. A proxy to the memory that your application needs. She will ensure that your application gets the memory it wants, as long as it can be made available.  

Before we jump head first into how exactly garbage collector does her job, we need to look at the types. Yes, you remember that you have two types – value and reference types. Value types are stored in the stack. That means, the moment the method comes to an end, the stack is completely cleared. Stack is cleared by the CLR (not the above mentioned garbage collector).  

The other type I.e. reference types are the ones that go to the heap. The heap is the domain of the garbage collector. Garbage collector rules over the heap. The garbage collector uses what is called as 'mark and compact' algorithm.  

How this works is like this. Garbage collector understands that it cannot be clearing up memory all the time. That's because garbage collector knows that cleaning memory also has a performance hit.  Which is why, garbage collector becomes active only when there no new memory to assign to objects asking for it. As long as there is room to give for new objects, it stays put. 

Once the memory is full (or about to become full) it becomes active. At this point, the garbage collector beings 'marking' object in the memory. The garbage collector goes through the items in the memory and finds 'living' items. A living item is an item that is referenced by what is called a 'root' item. Root item means, it is either a static field or a method parameter or a local variable or a CPU register. Once all the items have been checked (and marked if they are living), the garbage collector will remove all the 'dead' items from the memory, freeing up memory. 

The live items are all moved to be together. This is the packing part of the garbage collector activity. The live items are all packed to one side of the memory. These live items are 'promoted' by being assigned a higher generation. The rest become generation 0, and they are cleared up. I just realized that this is the same thing I said before about 'dead' items.  

Now, let's move on to something that is not exactly possible by garbage collector. You see, garbage collector works best with managed items. Unfortunately, an application cannot be built with managed items or managed resources only. For instance, an object of your custom type is a managed item or managed resource. That is the something garbage collector handles really well. No problems there. When you use a file in your program that file is an 'unmanaged' item or 'unmanaged' resource. Garbage collector cannot work with that since the file itself is stored outside, somewhere else. Not in the actual memory that comes under the purview of garbage collector.  

That means, the onus on handling with these unmanaged resources is on you. That means, you no longer have the option of depending on garbage collector for your memory related dirty work. It is now up to you to handle these issues. With unmanaged resources anything can go wrong. The file you are writing over a network, may suddenly become unavailable. You cannot let your application crash. 

For this purpose, c sharp gives you something called 'finalizer'. You specify a method as finalizer. In this method you do all the freeing of unmanaged resources. And then, you are free to do other activities on your unmanaged resources. For instance, you are writing to a file. Then, after you are done, you want to delete it. However, unless the file has been properly closed, delete won't happen. That is where finalizer comes into play. You will write the file close code in the finalizer. Then, thanks to the finalizer, your file is definitely closed, and you are now free to delete that file. 

Now, the tricky thing about finalizers is that, you cannot call them. Yep, that's right. It's disappointing but this is another way of c sharp making sure your application remains robust. However, the finalizer is called by garbage collection when it becomes active. This ensures that all resources are released and that means, once the garbage collection has occurred, you can be sure that the finalizer has been called. There is also the minor scenario where you try to do a unmanaged resource operation such as deleting a file but the finalizer is not done yet. That is why you can even wait for finalizers to finish. This way, you can be definitely sure that yes your unmanaged resource is handled well.  

However, here is that problem. What if the garbage collection never happens? That means the finalizer was never called, and that means your unmanaged resource is still doing something. Your application will fail. You can call garbage collector manually all the time. That will slow down your application like a crazy person.  

In order to ensure that you don’t place all your bets on garbage collection, c sharp provides you with something else. It gives you the IDispose interface. It contains one method (called as Dispose) which will, the moment it is called, it will free all unmanaged resources right away.  

Now (yes, this is going on and going but memory management is a complicated topic), what if something goes wrong before you use the Dispose method? That is where you use old try/finally concept that grabs unexpected errors. So, we are looking at a combination of try and catch and then calling dispose to make sure that the unmanaged resource will never mess with your program flow.  

Now, use those three – try finally and dispose – is good but it increases the amount of code you write. When you are working with many, and I mean many unmanaged resources, you will have to write this again and again. If you have a hundred files, the code keeps growing and growing. Since this is a frequently done thing, c sharp (of course) has a better solution. The solution is the 'using' statement. The using statement will bundle all the three into a single package. That way, you can code less and get done more.  

If you want to catch exceptions, you may also choose to include a catch in the above sequence, although using itself cannot be modified to include catch.  

Unfortunately, I am going to have to skip the code for this blog post. I am yet to blog about files, and we will revisit the topic of unmanaged resources then. 


Follow me on twitter, facebook and instagram for more updates. Thanks!

Explicit Interface Implementation

In our earlier blog post, we talked about the class heirarchy that comes with implementing interfaces and of course base and derived classes. 

One thing that I wanted to write separately was 'explicit' implementation of interfaces. By default, you do an 'implicit' implementation of interfaces. This is another one of those encapsulation stuff designe to hide methods from the interface. When you explictly implement an interface, the interface methods become unavailable to the to derived class objects.   

So, suppose, you have an Interface, I. class C implements I explicitly. You then proceed to create an instance of C, called c_1. You see, because of the explicit implementation of C (the type of c_1), c_1 will be unable to access methods of I. essentially, the methods of I are hidden from instances of C, even if th fact is that, it is C which is implementing I. 

Obviously, all this is confusing but find our attached code to see how it works. Here is our repo.


Follow me on twitter, facebook and instagram for more updates. Thanks!

Fields and Properties

When you are defining your own type, you will create some fields. Something like this. 

class water_bottle 

{ 

private string hello; 

//method to get this field will come here 

} 

Now that is a field of type int with the name 'hello'. That field can be accessed by a method (since the access modifier is private, and hence outsiders don’t have direct access) and do stuff with it. Making it private is a good design, and it's pretty neat. 

However, suppose, tomorrow you no longer wish to have 'hello' to be of type double. Perhaps, another custom type that you have defined. Then, it would become difficult to change. Further, perhaps, you want further control over how your data members are accessed. Perhaps your type may be derived by another type, and override some methods. Essentially you want to encapsulate, even more than what is already available. 

Bottom line, you wish to follow the design principles of object oriented development. If so, c sharp gives you properties which encapsulate the fields.  

Instead of the above code, you will do something like this. 

<code snippet here> 

Thanks to properties, you are now even more control in how your data is accessed by anybody including your own type definition methods. The get and set are called 'accessors'. They help you define how you get and set values from the fields. On the outset, it may look like methods. You may even argue that you could write a 'get' and 'set' method, mimicking this behavior. There is nothing wrong with that. In fact, you may very well do that.  

However, you can keep defining your own methods to get/set values, but what happens when you have hundreds of fields? Will you keep writing methods for each and every one of them? Of course, I have already described above the extra benefits. Overall, when you want fine grain control over your data, you are better off using properties than fields. 

Of course, I must note here that, using fields (without properties) is no crime and nor does it make your project design bad. In fact, some projects go with a combination of fields and properties. 

As always, find code in our repository here. 


Follow me on twitter, facebook and instagram for more updates. Thanks!

Abstract and Sealed Classes

Now that you are neck deep (or immersed if you are over enthusiased) in classes and inheritance and interfaces, you need to know how to lock down your classes.  

Abstract class is one that cannot have objects of its own. That means, you want (or force) this class to be used as the basis on which other classes are built. At the same you also want to make sure that nobody actually uses this class directly by creating instances of it. This is almost like interfaces (they also force a certain outline) but unlike interfaces, your abstract class contains all of its definitions.  

In fact, if you wish you can make some methods in your abstract class 'abstract'. That means, the definitions will have to built by the derived class. This way, you ge the best of regular classes and interfaces.  

Sealed class is the opposite of abstract class. When you seal a class, you are pretty much packing it tight. Folks can create as many objects out of it, nobody can reuse the code in your sealed class. This is why structs (which we discussed in our earlier blog posts) cannot be inherited, due to their sealed nature.  

For this post, I am skipping the code sample. As always, if you need a code sample, you know where to reach us.


Follow me on twitter, facebook and instagram for more updates. Thanks!

our code repository is up - for c sharp

Okay, so, we finally did it. 

As mentioned in earlier posts, many of our study nildana interns are pursuing a microsoft certification in c sharp. Many of our posts refer code samples at our repository. While our code was always ready, the online repository wasn't. So, we have it now. 

You can head over to our code hub

That will contain all of our code samples. Specifically, c sharp stuff is here 

Well, there is not much else to do about it. 

Follow me on twitter, facebook and instagram for more updates. Thanks!

Access Modifiers

Without access modifiers, most of the magic of encapsulation would work. A class without properly used access modifiers (or an assembly or a method) is like a house without locks. Anybody can do anything and before you know thing, things are going down the drain.

So, there are a total of five access modifiers. Here is a quick list and what they do.

Public

This means, anybody can use it. It cannot any more simpler than this. Does this mean, another class can just access it, perhaps create issues again. For instance, methods are usually public. So, that would create some problems, you would think. The thing is, methods can be called, but the internals of a method are still under your control.

That means, just because someone can access some members of your type, does not mean bad things will happen. It just means that you give them access to the extent they require.

Internal

This means, the given member is only available in the current assembly.

Okay, so assemblies. Yeah, if you are only beginning to learn programming (which is probably the case if you are reading my blog in its dictated sequence), you don’t need to know about that. However, just remember that when you prefix it, you can only use these within the assembly.

Protected

This keyword helps you restrict the usage to the 'containing class' and 'derived classes'. That means, only the members of said class can use it and those that are derived from said class.

Protected Internal

A combination of the last two. This means, either of the above two. Within assembly or derived.

Private

Usage restricted to containing class.

I don’t have a sample code for this because the stuff is self explanatory.

Follow me on twitter, facebook and instagram for more updates. Thanks!

Encapsulation and Access Modifiers

If you have been following our tutorials and associated code, you would have noticed that we have frequently used words such as 'private', 'public' and rarely, 'protected'. You probably already have a vague idea what these things do but for the sake of completion, I am including that here.  


The important concept is what these things are doing, and that is encapsulation. A capsule is something that keeps its contents separate from the outside world. It also allows the capsule's contents to be consumed in a certain way. Let's take the example of a medical capsule. It's like a container, and inside the container are its actual contents.  


There is no way for you to access the contents of the capsule (without breaking it but that is not how its meant to be used) without swallowing it. Once you swallow the capsule, the outer covering will dissolve in the stomach, allowing for the medicines to be released. Thanks to this 'encapsulation' the contents of the capsule has been delivered just the way it was meant.  


That is also what encapsulation does in c sharp (and any other object oriented programming language for that matter), allowing you to hide stuff that should be completely hidden. Further, you get to choose how outside elements can access what's inside. Which means, you can control how the types (and the objects) designed by you will behave, no matter where they are used.  


Another example I can think of is planning a party or a festival at home. It is your home where you are hosting the party or festival. You are going to invite a lot of people into your home. At the same time, just because you invited people, does not mean you want them to roam around in every part of your home. There are some places where you don’t mind them going, and other places they are forbidden. Some friends will be able to use special rooms while some can only sit in the main hall.  


Every type that you define is like this party or festival. You want your types to be used, but you decide who gets to use how much and to what extent. That is what encapsulation is all about. To do this, c sharp provides you with many 'access modifiers'. Think of access modifiers like those security guards in a museum. Different types of security guards allow for different types of access. For instance, you may have seen the guards at ATMs (who don't do anything, but that is of course part of their job) while then there are guards who protect movie stars and government folks who can do lots of things.  


In c sharp, depending on how completely open or completed closed or (as is normally the case) something in between, you want to access to be, you decide which access modifiers to use. 


Continue on to our next blog where you can find out more about access modifiers along with sample code.


Follow me on twitter, facebook and instagram for more updates. Thanks!