2019 Educational Goal

I am a believer in setting goals in every aspect of life. My 2019 educational goal is a bit ambitious but achievable. I didn’t realize it at the time but this goal is going to change my focus a bit. In order to complete this goal successfully, I am going to have to spend a lot of my time away from work consuming educational media instead of binging on Netflix or re-watching all of Game of Thrones.

Read 100 Books

I should be able to do this fairly easily as long as I don’t get distracted. I go through phases where I devour everything I get my hands on. Occasionally, though, I get distracted by a book because I either find it boring or it just isn’t exactly what I want or need at the time and I drag my feet. Right now I am struggling with a book that everyone seems to love but I can’t seem to get into which is Jordan Peterson’s 12 Rules of Life: An Antidote to Chaos. I can’t seem to get into it so I will probably have to put it down and move on. Maybe I can pick it up again later. Deep Work was another book like that for me. I still haven’t read it. The guidelines for this goal are that I can re-read books I have read before and enjoyed and I can read any genre. I am not restricted to non-fiction.

This is good for me because I have a list of favorites that I re-read every year. It would definitely hinder me if I didn’t count them. Here is my re-read list for 2019. Every year the books change as I grow out of some and add new favorites.

  1. Rich Dad, Poor Dad by Robert Kiyosaki
  2. Atlas Shrugged by Ayn Rand
  3. Set for Life by Scott Trench
  4. The 4 Hour Work Week by Tim Ferriss
  5. The Richest Man in Babylon by George S Clason
  6. The Compound Effect by Darren Hardy
  7. I Will Teach You To Be Rich by Ramit Sethi
  8. The War of Art by Steven Pressfield
  9. Be Obsessed or Be Average by Grant Cardone
  10. The Miracle Morning by Hal Elrod
  11. The Prince of Tides by Pat Conroy
  12. Think and Grow Rich by Napoleon Hill
  13. The E-Myth Revisited by Michael E Gerber
  14. Start with Why by Simon Sinek
  15. The Lies of Loche Lamora by Scott Lynch
  16. Cashflow Quadrant by Robert Kiyosaki
  17. Your First 100 by Meera Kothand
  18. Never Split the Difference by Chris Voss

So, 18% of my quota will be re-reads but that is okay. Perhaps this is the year I take better notes so I can just read the notes in a few minutes instead of spending hours in the book. Notice that only three are fiction. I will likely read a lot of fiction but only in very strict circumstances do I read fiction over and over. The Wheel of Time was an exception. So are the Stormlight Archives. Oh well, those massive tomes won’t be on my list this year. This breaks down to 2 books per week and since I have spent over a week trying to struggle through 12 Rules, I need to get moving.

Complete 25 Online Courses

Some of these will be brief and some will not. There are several areas I am going to focus on this year. Fulfillment by Amazon, Python, Machine Learning, and advanced Mathematics are all high on my list. I already have several of these purchased but I still need to schedule them. The length of the courses will be from 3 hours (FBA, Python) to 40 hours (Machine Learning). I would also like to brush up on Spanish and pick up another programming language but there might not be time for all of that. Still, 25 is a lot. It means I have to complete one course every two weeks. So far, I haven’t scheduled any time and that is something I really need to start doing. Part of me is insisting on getting it right. I don’t want to waste a slot on something I am not 100% certain on.

Listen to 250 Podcasts

This one might seem hard on the surface but I think it will be the easiest of the three. I can listen while exercising and driving so the time is there for sure. I am focusing on The Bigger Pockets Podcast, The Indie Hackers Podcast, and the Smart Passive Income Podcast. Those three alone will keep me busy for at least two years. And, they come out with new content every week.

This breaks down to about 5 per week and that means one per day. I can probably do 500 just this year but we will see. At some point, I may have to switch to audiobooks in order to hit my 100 books but time will tell.

Conclusion

I would love to hear from anyone that is actively planning their educational goals. Everyone needs an accountability buddy and one more won’t hurt. My goals are a bit ambitious I think but I will only know when the time gets closer. If they aren’t ambitious enough, I will raise the counts but I won’t lower them. I will just have to focus a bit more each week to get on track.

Top 10 Most Common C# Interview Questions

Through the years, I have been in hundreds of interviews and phone screens as the interviewer or interviewee. Here are 10 of my favorite questions with answers. Not all of these are strictly specific to C# and might target the .NET Framework or core programming concepts.

  1. What is C#?

    C# is a 3rd generation general purpose programming language created by Microsoft. It is used across many different platforms including web (ASP.NET, ASP.NET MVC, ASP.NET Core), Windows Desktop (Windows Forms, WPF, UWP), Mobile (Xamarin, UWP), gaming (Unity3D, XNA), and web services (WCF, Web API) just to name a few.

  2. What is an object?

    This question requires a bit of caution because there are several different answers depending on the context. Typically, the context is object-oriented programming. In OOP, an object is a class. In computer science, an object is everything including a variable, function, pointer, etc. In databases, an object is a table, a view, a stored procedure, etc.

  3. What are the four core tenets of Object-Oriented Programming (OOP)?

    1. Abstraction
      Abstraction is a form of art, really. It is the act of hiding away the complexity of implementation. For example, the .NET Framework is a massive set of abstractions laid over the internal workings of the operating system you are targeting. You don’t need to understand how it interacts with the operating system. However, it is very helpful to understand how the .NET Framework classes work but not always necessary. If you look for them, you can find abstractions everywhere.
    2. Encapsulation
      Encapsulation has two fundamental parts. First, encapsulation is also known as information hiding. It enables you to protect or hide the implementation details or data because those details are not important to the implementor. Second, because the implementation details are hidden, it appears that an entire implementation chain is a single unit. A simple example of this is a public property that uses a private backing store in a class. The implementor cannot see anything past the public property but there might be dozens of operations hiding behind it.
    3. Inheritance
      Inheritance allows you to create a base class with functionality and reusing or overriding that functionality in classes that inherit or derive from that base class.
    4. Polymorphism
      Polymorphism means ‘many forms’. A real-world scenario may look like this. You are picking up data from a queue. You don’t really have any way of knowing what that data will actually but you do expect it to conform to some agreed-upon contract. If the data is type A, you will instantiate a new type A processor. If the data is type B, you will instantiate a new type B processor. And so on for type C, D, etc. To avoid creating processor-specific implementations, you just create an interface that all the processors implement and then you can call a specific method on each processor such as DoWork() and not really care which processor is actually running. This is also why polymorphism is also well known by the moniker ‘one interface, many functions’.
  4. Does C# support multiple inheritance?

    No. There is no other acceptable answer. If you look at the definition of inheritance, it says class. It does not say interface. You do not inherit from an interface, you implement an interface. The answer is no.

  5. Explain the benefit of implementing the IDisposable interface.

    IDisposable allows for a very easy way for a class to release objects external to your application. This release will ensure that objects that implement the IDisposable interface are garbage collected and the external resources they use are no longer kept in use. For example, a connection to a database. Eventually, the database would run out of connections. Another example is an XmlWriter. Disposing the XmlWriter will release the StreamWriter object the XmlWriter references which will release the FileStream the StreamWriter references which will actually release the file handle used by the FileStream.

  6. What are namespaces?

    Namespaces are used to organize code into logical containers. For example, the System.Data namespace has classes that work with data and System.Configuration contains classes that work with configuration. We can apply namespaces to our own projects to gain as much control as we desire over the organization of our code.

  7. Explain the different access modifiers available in C#?

    There are several:

    • public – Visible to all
    • private – Visible only to the code in the same instance
    • protected – Visible to the instance and any that inherit the instance
    • internal – Visible only to the objects in the same assembly
    • protected internal – Visible only to the instance and any that inherit the instance
    • private protected – Visible only to the instance and any that inherit the instance in the same assembly
  8. What are boxing and unboxing?

    Boxing and unboxing is actually an important part of the .NET Framework’s common type system. Boxing is the process of converting a value type such as an integer to an object type. Unboxing is the process of converting the object type to a value type.

  9. What is an interface?

    An interface is a contract. It contains the signature or declaration of methods, properties, and events but never the actual implementation. When you implement an interface, you are agreeing to the contract of the interface and must explicitly implement all the containing methods, properties, and events.

  10. What is the difference between a reference type and a value type?

    I have written on this topic before. In short, a reference type is stored on the heap while a value type is stored on the stack. This is important because of the way you change the value. Read the linked article for a lot more information.

I hope you have enjoyed this post and possibly have learned a bit. I always enjoy reading interview posts and articles because they change over time. Recently, during a long span of really poor candidate quality, we returned to the basics as this post shows. These interview questions are very simple.

2019 Is Five Days Away – Five Days Until Your Best Year Ever

This post is a little different than others I have done before. Today, we are going to discuss goals, goal setting, and best practices,. There are 5 days left before New Years. There is never a better time to tackle a new goal than right now!

S.M.A.R.T. Goals

Unless you have been hiding under a rock, you know what S.M.A.R.T. goals are. There are other systems that may be just as effective but I like the SMART system because it is simple and that is a very important piece of goal achievement. It should not feel like you are fighting a system to achieve your goals. Achieving ambitious, meaningful goals is hard enough as it is.

S – Specific

Use the 5 W’s to make your goal as specific as possible.

  1. Who is involved?
  2. What do you want to achieve?
  3. When am I going to do this?
  4. Where am I going to do this?
  5. Why is this important?

Asking these questions will reinforce your ideas and ensure you are setting goals that you want to accomplish. If you can’t nail it down, you shouldn’t be chasing it. Doing this exercise may also change your perspective and make the goal easier to achieve.

M – Measurable

I guess we have all done it. We have all created goals for ourselves such as ‘Lose weight’ or ‘Make more money’. The problem with goals such as these is that there is no real way to know when it is done or when you have accomplished it. How much weight do you want to lose? Put an exact figure on it. ‘Lose 10 pounds’ or ‘Get my weight down to 180 pounds’ are both infinitely better than ‘Lose weight’. ‘Increase my monthly income by $2000’ or ‘Increase my monthly income to $4000’ are both infinitely better than ‘Make more money’.

If your goal is ‘Lose weight’ and you lose 10 pounds in January and gain 5 pounds in February, you have technically still lost weight but the goal should be your endgame. When you achieve that goal, it should be obvious and you should be able to stand tall and say I achieved that. It makes a massive difference.

It is said that what gets measured, gets managed. If you have a goal that can be measured, you are much more likely to achieve it because it isn’t vague. You are able to gauge your progress over time and you can compare your current state with the desired state and know whether you need to turn on the gas or if you are already on track.

A – Achievable/Attainable

There are two ways to look at this part of a SMART goal and I recommend you use both because they both offer value.

Is your goal attainable? Is it realistic? Is it something you want to do? Are you likely to stick with it till the end?

Is your goal achievable? A good goal will make you stretch to achieve it but it should still be possible. What will you have to change in order to achieve this goal? What new habits will you have to put in place? You should be looking for missed opportunities and ways to change the state of your life to accomplish your goal.

R – Relevant

This section of the goal is extremely important because it can give you insight into your own heart and mind. Why do you want to accomplish this goal? Is this goal you? Does it match with your personality or does it go against who you are? Does it agree with other goals you are currently working through or does it go directly against one or more of them? Why now? Why you? The point of this exercise is to determine your WHY. Your WHY might be the only thing that keeps you going at times so don’t overlook its importance.

T – Time-Bound

Every good goal has a deadline. You should put an exact date on it. Most New Year’s Resolutions have no date stamped on them so they typically die by the end of January. Don’t do that to yourself. Based on your goal, what is a reasonable time frame needed to accomplish it?

Going Beyond S.M.A.R.T.

SMART goals are effective. However, you have to go further if you want great results. Here are four tips for achieving goals that I have found very useful.

First, if you have a year-long goal as most ambitious goals are, it isn’t enough that you have set that goal. You need to break it down. Most goals that take more than a few weeks to accomplish are just too big to wrap our heads around. Start by breaking that goal into parts. What can you accomplish this quarter that will put you on the fast track to achieving that goal? What can you accomplish this month? What about this week? What can you do today? What can you do right now to move forward? Another reason to do this is that it can create a series of smaller wins for you which should increase your overall chances of success and your motivation level.

Second, create a plan. You do not have to be fancy. You can use Trello. You can use Excel. You can use pen and paper. Start by taking the monthly or quarterly goal and listing out all the tasks that have to be done in order to accomplish your goal. Don’t worry too much about accuracy. There isn’t a penalty if you get it wrong. You can always delete it later but list out everything you can think of. Get it out of your head and into a trusted list that you can review to track your progress.

Third, write your goal down. According to research, you are 42% more likely to achieve your goal if you write them down. That is like free money. Why would you not? But don’t just do it once. Grant Cardone is famous for writing his goals down twice daily. Whether or not you like Mr. Cardone, you can definitely take a cue from his success and do the same. Twice a day might be a bit much but once a week is definitely doable and will likely increase your chances of success.

Finally, be consistent. You have your goals broken down into manageable bites but that isn’t getting them any closer to complete. Ideally, you are doing monthly, weekly, and daily planning and review sessions where you review what has been completed and deciding what needs to get done in the upcoming time period to keep you on track or to put you back on track. These sessions can be as simple or elaborate as you would like to make them. Typically, I spend less than 10 minutes in each session but I put a lot of thought into the session before it happens.

Conclusion

I hope you found this post helpful. Goal setting is one of the most important factors in the success of our lives. I am really looking forward to 2019 and I am determined to make it my best year ever.

Designing an Effective Exception Handling Strategy

In applications large and small, the role of exception handling is very rarely a first class experience. Instead, it is often haphazardly put together if thought about at all. In this post, we will explore some ideas about exception handling that are often considered best practices. For the purposes of this article, assume we are building a large-scale web-based application with three tiers: UI, Logic, and Data Access.

Best Practices

Handle Each Exception Only Once…

…unless you have a very good reason not to. It is poor design to capture an exception and then rethrow it without adding value. In the mythical application we are building, if we capture an exception in the data access layer and then rethrow it and allow the business logic layer actually handle it, we have a pretty obvious code smell. Why did we capture that exception at all? Always let exceptions boil up to the layer that can handle them.

The Best Exceptions Never Happened

You should go through as much trouble as necessary to prevent exceptions from happening in common scenarios where we have a known possible error condition. For example, if you have a Contact object and you need to check the First Name of that contact, if there is any chance at all that the Contact object itself may be null, you should test for that condition to avoid an exception.

Be Consistent

This is one of the most important best practices available and is actually the reason to develop a strategy at all. Before sitting down to write an application, you should already have an exception handling strategy fully baked and ready to implement. There are few greater sins than finding ‘special cases’ in the middle of a well-thought-out exception handling policy. It goes against the grain and offends our senses. Don’t do this.

Be Specific When Possible

This one should be obvious. If you know that a SqlException may occur, catch it specifically. Try hard not to just default to catching the all-encompassing Exception type. Yes, it may require a bit more work but if you create good habits, they will serve you well for a long time.

Create Your Own Exception Classes When Necessary

Create your own exception classes to throw when it makes sense. If you constantly find yourself throwing an Exception with similar error messages, this might be an indicator of a possible exception type that should be created. There are no good hard rules here. Just do it where it makes sense to get the most bang from your buck.

Don’t Create Your Own Codes

Avoid giving codes to your exceptions. 101010 won’t mean anything compared to ‘Validation error. Field is required.’ The message makes a whole lot more sense than 101010. Please, don’t do this. It doesn’t make you smart or the system more sophisticated. The best case scenario here is that you end up being responsible for either fielding questions about what the different codes mean or publishing a list of the codes and their meanings and that means you are responsible for also keeping it up to date. Don’t you already have enough to do?

Don’t Eat Exceptions – They Are Bad For The Digestion

If you are eating or swallowing exceptions, you should have a very, very compelling reason. Why even catch them if you aren’t doing anything with them? They should, at the very least, be logged. There are certain exception scenarios that your application should be able to recover from, surely, but swallowing (ignoring) exceptions is a bad way to do that.

Logging

Again, at the very least, you should be logging every exception that occurs in your system unless you have a very good reason not to. Err on the side of caution here. Log it. If you are struggling to decide if it should be logged, go with yes, it should be. You should not log them when you have a compelling reason, not if you are indecisive.

Conclusion

If you aren’t designing an exception handling policy, you have a problem that is begging for a solution and this problem has been solved a million times. There is plenty of information out there.

In this post, we looked at some (not all) best practices that should be considered when designing an exception handling strategy. I hope you found it useful and can incorporate some of the suggestions into your own workflow and design an effective exception handling strategy.

Shallow Copying vs Deep Copying in C#

In this article, I will show examples of shallow copying and deep copying in C#, we can examine the differences, and I will give you a few pointers.

Shallow Copying and Deep Copying

Shallow copying isn’t a new concept to most programmers. We do it all the time. Reference types (objects) are just a reference to a value on the heap. If this is not familiar to you, read this article. Here is a pretty simple scenario to show this functionality.

Figure 1.1 – Shallow Copy Example

Contact c1 = new Contact
{
    LastName = "Galt",
    FirstName = "John"
};

Contact c2 = c1;

c2.FirstName = "Who is John";

Console.WriteLine($"c1.FirstName: {c1.FirstName}");
Console.WriteLine($"c2.FirstName: {c2.FirstName}");

This is pretty straightforward. I am creating a contact object and then copying the reference to that object to another variable. Changing one of them changes both of them.

Figure 1.2 – Output

c1.FirstName: Who is John
c2.FirstName: Who is John

There are several methods available for creating deep copies but I prefer MemberwiseClone.

First, we need to change the model object to inherit the ICloneable interface and implement that interface simply.

Figure 1.3 – ICloneable Implementation

public class Contact : ICloneable
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
    public Guid ID { get; set; }
    public string PhoneNumber { get; set; }
    public Company Company { get; set; }

    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

This will give us access to the Clone method and open up a path for Deep Copying.

Now, when we run similar code to before, the results will be better.

Figure 1.4 – Getting a Slightly Deeper Copy with Clone

Contact c1 = new Contact
{
    LastName = "Galt",
    FirstName = "John"
};

Contact c2 = (Contact)c1.Clone();

c2.FirstName = "Who is John";

Console.WriteLine($"c1.FirstName: {c1.FirstName}");
Console.WriteLine($"c2.FirstName: {c2.FirstName}");

Figure 1.5 – Output with ICloneable

c1.FirstName: John
c2.FirstName: Who is John

This actually creates a deep copy of the Contact object but doesn’t go far enough. It is not a true deep copy.

Figure 1.6 – The Company Object

Contact c1 = new Contact
{
    LastName = "Galt",
    FirstName = "John", 
    Company = new Company
    {
        Name = "The John Galt Line"
    }
};

Contact c2 = (Contact)c1.Clone();

c2.Company.Name = "Rearden Steel";

Console.WriteLine($"c1.Company.Name: {c1.Company.Name}");
Console.WriteLine($"c2.Company.Name: {c2.Company.Name}");

This is similar to our earlier scenarios. After the Clone operation, c2 is a completely new object but c1.Company and c2.Company both still have the same reference to the same object on the heap.

Figure 1.7 – Output from Company Reference

c1.Company.Name: Rearden Steel
c2.Company.Name: Rearden Steel

So, there is an option available to us. One that is actually pretty easy to implement and will get us where we are looking to go. It is a two-step process. First, implement ICloneable on the Company object. This will enable us to create a clone of the company object. Second, we need to change the Clone method on the Contact object to take advantage of the fact that Company is now cloneable as well.

Figure 1.8 – Deep Copy

public object Clone()
{
    Contact contact = (Contact)this.MemberwiseClone();

    contact.Company = (Company)Company.Clone();

    return contact;
}

Here we are simply exerting a bit more control over the Clone method by also cloning object properties on the Contact object which creates a true deep copy.

Figure 1.9 – Deep Copy Output

c1.Company.Name: The John Galt Line
c2.Company.Name: Rearden Steel

Conclusion

As this post shows, creating a deep copy is not as simple on the surface as it seems and it actually requires a strategy to create deep copies. It requires an implementation from top to bottom throughout the models of your project and should be implemented based on need and usually not by default.

Extension Methods 101

Extension methods have been available in the .NET Framework since 3.0. If you haven’t created one before, the chances are very high that you have at least used one, possibly without realizing it. In this post, we will explore what extension methods are, how to create them, and compare them to regular class methods.

What are Extension Methods?

Extension methods are methods that extend the functionality of a class. They do not have to belong to the class or the library of the class they extend and can be created by anyone for just about any class available. This gives us a great amount of power to make objects in the .NET Framework and external libraries more useful to us. We can even create them for our own classes when it makes sense.

How do Extension Methods Differ From Normal Methods?

Extension methods appear almost identical to methods already in the class to consumers with one small caveat. That caveat is that you must reference the namespace of the extension method before it can be used. Realistically, however, extension methods are quite different than normal methods in a class.

Extension methods and the class they exist in must be static. Extension methods also must have at least one argument: the object they are extending. However, you don’t have to pass that object in. Before I confuse you, let’s take a look at a quick example.

Listing 1.1 – A sample extension method

public static class ContactExtensions
{
    public static string FullName(this Contact contact)
    {
        string fullname = string.Empty;

        fullname = contact.FirstName;

        if(!string.IsNullOrEmpty(fullname))
        {
            fullname += " ";
        }

        fullname += contact.LastName;

        return fullname;
    }
}

Both the ContactExtensions class and the FullName method are static. The first and only argument in the FullName method is a Contact argument but note the this keyword. It is the type we are operating on and it is what makes extension methods possible. We don’t have to supply it and it provides the context for the FullName method. Now, let’s look at a quick implementation.

Listing 1.2 – A simple implementation

Contact contact = new Contact
{
    LastName = "Galt",
    FirstName = "John"
};

Console.WriteLine($"First Name: {contact.FirstName}");
Console.WriteLine($"Last Name: {contact.LastName}");
Console.WriteLine($"Full Name: {contact.FullName()}");

See that the call to contact.FullName is a method call but that we don’t have to supply the Contact argument. It just seems like a method already existing on the Contact object.

Listing 1.3 – Output

First Name: John
Last Name: Galt
Full Name: John Galt

You can, however, have other arguments available for an extension method. Those arguments may also be given a default value but the normal rules apply there.

Listing 1.4 – An Extension Method With an Additional Default Argument

public static string DisplayName(this Contact contact, string separator = ",")
{
    string displayname = string.Empty;

    displayname += contact.LastName;

    if(!string.IsNullOrEmpty(displayname) && !string.IsNullOrEmpty(contact.FirstName))
    {
        displayname += separator;
        displayname += " ";
    }

    displayname += contact.FirstName;

    return displayname;
}

In this example, the extension method has a second argument but supplies a default value for that argument. And we can call the new extension method easily with: Console.WriteLine($"Display Name: {contact.DisplayName()}");.

Listing 1.5 – Output

First Name: John
Last Name: Galt
Full Name: John Galt
Display Name: Galt, John

Conclusion

Extension methods can be very handy when used with objects outside of your own control. I hope that adding this tool to your belt will allow you to create a better experience for yourself and your colleagues.

An Introduction to Structs in C#

A struct is a value type that is often used to house a group of related variables, such as the points of a rectangle, together. Structs share many characteristics with classes but they are, at the same time, very different. In this post, we will explore those commonalities and differences and explore some use cases for a struct.

What is the Difference Between a Struct and a Class?

As it turns out, a struct and class have many things in common. They both can have constants, fields, methods, properties, operators, events, constructors, and indexers. A struct can inherit from an interface but not from a class or another struct. Structs are value types while classes are reference types. If you don’t know the difference between a value type and a reference type, read this post. You can set the value of a struct from an external caller just like you would for a class. However, setting the values of a struct inside the struct itself is more difficult. You cannot initialize the properties to a default value and structs do not allow a default constructor because a default constructor is created automatically. If your struct has a non-default constructor, each property in the struct must be set in that constructor. A compile-time error will occur otherwise.

Listing 1.1 – A Simple Struct

public struct SurfaceStruct
{
    public int Width;
    public int Height;
    public int Area;

    public SurfaceStruct(int width, int height)
    {
        Width = width;
        Height = height;
        Area = Width * Height;
    }
}

When to Choose a Struct Over a Class?

Very rarely. There are two rules you should remember when deciding. First, since a struct is a value type, it resides on the stack. That means it should be kept to a very small size. 64 bits should be the upper limit, just like the designers of the .NET Framework have done. Second, ask yourself if any of the properties for the proposed struct make sense without the others. If they do, you should create a class. If not, a struct may be right for you. Also, if you are creating a struct and any of your properties are reference types, you should be using a class.

Conclusion

Structs are a valuable tool in programmer’s toolbelt but their uses are limited. In this post, we have looked at the differences between a struct and a class and when to choose one or the other. I hope it was helpful.

Constructor Chaining in C#

In this post, we will look at constructor chaining in C#.

What is Constructor Chaining?

Constructor chaining occurs when you use one constructor in a class to call another constructor on the same class. Often, because the constructors must have different signatures, you supply a safe or default value for the second constructor.

Listing 1.1 – Constructor Chaining

public MessagePrinter(string message) : this(message, 1)
{
            
}

public MessagePrinter(string message, int counter)
{
    for(int i = 0; i < counter; i++)
    {
        Console.WriteLine($"{i} - {message}");
    }
}

This will allow the default constructor to then call the second with a default argument specified for the counter value. However, I have a question for you. Which constructor executes first? If you said the default constructor, you would be wrong.

Listing 1.2 – Constructor Chaining Execution Order

public MessagePrinter(string message) : this(message, 1)
{
    Console.WriteLine("Constructor 1");
}

public MessagePrinter(string message, int counter)
{
    Console.WriteLine("Constrctor 2");

    for(int i = 0; i < counter; i++)
    {
        Console.WriteLine($"{i} - {message}");
    }
}

Figure 1.1 – Output from Listing 1.2

Constructor 2
0 - Test message
Constructor 1

Conclusion

Since the default constructor is called last, I have to wonder if there is any inherent value in constructor chaining at all. Any work that would be done in the default constructor is executed after the chained constructors so it may even be a bit dangerous. I know there are circumstances that demand a default constructor, however. Those scenarios are still valid but just be aware of the risks.

Using the yield keyword in C#

The yield contextual keyword was first introduced in C# 2.0 and despite that fact, it is rarely used. Perhaps it is not a well-known feature or perhaps it is misunderstood but it has plenty of uses. In this post, I will demonstrate how to use the yield contextual keyword and discuss some common scenarios where it would be useful.

yield

What does the yield keyword do?

The yield contextual keyword returns an IEnumerator<T> collection and returns the items in that collection one at a time. If that seems confusing, think of a method that returns a list of items. Yield will allow you to return an IEnumerator<T> collection without declaring the collection.

Listing 1.1 – ContactValidator.cs

public static class ContactValidator
{
    public static IEnumerable<string> GetErrors(Contact contact)
    {
        if (string.IsNullOrEmpty(contact.LastName))
        {
            yield return "Last Name is required.";
        }

        if(string.IsNullOrEmpty(contact.EmailAddress))
        {
            yield return "Email Address is required.";
        }

        if(string.IsNullOrEmpty(contact.PhoneNumber))
        {
            yield return "Phone Number is required.";
        }

        if(contact.ID == Guid.Empty)
        {
            yield return "ID is required.";
        }
    }
}

Ignore that the ContactValidator class and GetErrors method are static. It doesn’t matter and it doesn’t have to be. The method is straight-forward. It is checking the values of several different properties and if each of those properties does not meet requirements, an error message is returned.

Listing 1.2 – Contact.cs

public class Contact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
    public Guid ID { get; set; }
    public string PhoneNumber { get; set; }
}

Listing 1.3 – Testing the yield functionality

static void Main(string[] args)
{
    Contact contact = new Contact
    {
        FirstName = "Ted"
    };
            
    List<string> errors = ContactValidator.GetErrors(contact).ToList();

    foreach(string err in errors)
    {
        Console.WriteLine(err);
    }

    Console.ReadKey();
}

This will create a new contact that has all the required and validated fields missing. Looking at the validation code in Listing 1.1, what are the expected results?

Listing 1.4 – ContactValidator results

Last Name is required.
Email Address is required.
Phone Number is required.
ID is required.

Yield allows this by returning the error messages one at a time as they occur but only returning after the method has completed.

One more quick example.

Listing 1.5 – Use of yield break

public IEnumerable<int> GetMultiplesOfSix()
{
    for(int i = 0; i < 100; i++)
    {
        if(i%6 == 0)
        {
            yield return i;
        }

        if(i > 48)
        {
            yield break;
        }
    }
}

In this example, we are using yield inside of a loop. If the value of i is divisible by six, it is being returned. However, if i is greater than 48, we are exiting the loop through the use of yield break.

Listing 1.6 – Output

0
6
12
18
24
30
36
42
48

Conclusion

Yield offers a different way of doing things but I actually like using it in my code. It means less code because I don’t have to create my own collection or manage it and it makes for a bit cleaner code. However, because it isn’t widely used or even known, I am careful in its application.

Working With Optional Arguments in C#

Optional arguments were introduced in C# 4. They are valid for constructors, indexers, methods, and delegates. In this post, I will cover the basic information needed to use them correctly.

What are Optional Arguments?

Optional arguments are exactly what they sound like: arguments that you are not required to supply because they have a default value already specified. If no value is sent for that argument, the default value is used. If you don’t want the default value to be used you simply supply another value.

Rules for Optional Arguments

Optional arguments do have to follow a couple of rules, though. First, in the argument list of the method, constructor, etc they must be defined after all required arguments.

Listing 1.1 – Optional Argument Example

public void DoSomething(int reqArg1, int reqArg2, int reqArg3, int optArg1 = 1, int optArg2 = 10, string optArg3 = "Hello")
{
    Console.WriteLine($"reqArg1: {reqArg1}, reqArg2: {reqArg2}, reqArg3: {reqArg3}, optArg1: {optArg1}, optArg2: {optArg2}, optArg3: {optArg3}");

    Console.ReadKey();
}

In this example, the three required arguments are defined first and the three optional arguments are defined last. You can tell that they are optional because they have a value assigned to them in the method signature.

Second, the types of values that can be assigned to an optional argument are limited to one of three scenarios:

  1. A constant value such as 1, 10, or “Hello”.
  2. An expression in the form of a new(valType) declaration where valType is a value type.
  3. An expression in the form of a default(valType) declaration where valType is a value type.

Third, you have two options for using the optional arguments. You can either supply a value for each of the optional arguments that come before the one that you want to give a different argument for.

Listing 1.2 – Using all optional arguments before the argument you want to supply a different value for.

DoSomething(10, 20, 30, 1, 50);

What we are really after in the example above is setting the value of optArg2 to 50. To do so, we have to set optArg1 as well.

There is another way, however. We can use named arguments. Instead of passing 1 to optArg1 and 50 to optArg2, we can just specify optArg2 using named arguments.

DoSomething(10, 20, 30, optArg2: 50);

One issue can arise from using named arguments, however. If you have two different methods that have two different signatures but have the same named arguments that are being used, the compiler will not know which you are trying to use and will result in a compile-time error. The only way to fix this is to change the name of the named argument being used. This is not likely to be a common problem, however, because the use of optional arguments should limit the need for multiple method overloads.

Conclusion

In this post, we explored optional arguments, what they are, and how to use them. They are not difficult to use and they can provide us with a much cleaner codebase when used appropriately.