Do you know when to use the different WCF Context Modes?

Let's talk about WCF's InstanceContextMode, give a brief overview of the possible values and determine when to use them.

InstanceContextMode is a property on the ServiceBehaviorAttribute class in .NET Framework 4.5. A developer will use the InstanceContextMode property to specify when new service objects are created.

Because the service object is not directly connected to the communicating channel, the lifetime of the service objects is independent of the lifetime of the channel between a client and the service application. The default value, PerSession, instructs the service application to create a new service object when a new communication session is established between a client and the service application. Subsequent calls in the same session are handled by the same object.

There are 3 context modes in WCF:

  1. PerCall
  2. PerSession (Default)
  3. Single

The default value, PerSession, instructs the service application to create a new service object when a new communication session is established between a client and the service application. Subsequent calls in the same session are handled by the same object. PerSession indicates that each service object handles requests from one client channel. A service configured for private sessions cannot typically support more than a few dozen (or perhaps up to a few hundred) outstanding clients due to the cost associated with each such dedicated service instance.

PerCall creates a new InstanceContext object prior to and recycled subsequent to each call. If the channel does not create a session this value behaves as if it were PerCall. After the method call returns, if the object implements IDisposable, then Windows Communication Foundation calls IDisposable.Dispose on it.

Single creates only one InstanceContext object. It is used for all incoming calls and is not recycled subsequent to the calls. If a service object does not exist, one is created. The singleton service is the ultimate shareable service. When a service is configured as a singleton, all clients get connected to the same single well-known instance independently of each other, regardless of which endpoint of the service they connect to. The singleton service lives forever, and is only disposed of once the host shuts down. The singleton is created exactly once when the host is created.

Which instance context mode to use and when

Per session (Default)

• When you want to maintain states between WCF calls.
• When you don't have very many concurrent connections and don't need to scale up.
• When you have light resource references

Per call

• When you want a stateless services
• When your service holds intensive resources like connection and huge memory objects.
• When scalability is a prime requirement.
• When your WCF functions are called in a single threaded model.


• When you want share global data through your WCF service.
• When scalability is not a concern.

Do you follow SOLID principles? If you don't, you may be doing yourself a disservice


S (SRP) - Single responsibility principle states that a class should have only a single responsibility 

O (OCP) - Open/closed principle states that software entities should be open for extension, but closed for modification.

L (LSP) - Liskov substitution principle states that objects in a program should be replaceable with instances of their sub-types without altering the correctness of that program. (See also design by contract.)

I (ISP) - Interface segregation principle states that many client-specific interfaces are better than one general-purpose interface.

D (DIP) - Dependency inversion states that we depend upon abstractions not concretions.

You will find that many higher level jobs, specifically jobs for domain, data or enterprise level architecture will require you know what SOLID is and abide by its principles. As you will see, SOLID is fairly straight-forward, however if you find that you don't understand any of the principles stated here, SOLID principles hedges against anti-patterns as well as problems with application coupling, rigidity and fragility. I urge you to do further research so you understand these principles. They are basic and fundamental principles that any good program would know.

Some cloud computing terms you should know about

Cloud computing is becoming a reality fast. More and more jobs are popping out that require you know what cloud computing is conceptually as well as who the top providers are in the industry. The two giant providers of cloud computing are Microsoft Azure and Amazon Web Services. Whether or not you use Azure or AWS is immaterial when it comes to needing to understand the following terms and concepts. It is immaterial because one could implement these concepts on their own if they wanted to without using the giants. A fair number of companies already provide SaaS to their clients.

Here are the 3 biggest concepts around cloud computing and a definition for each.

SaaS: Software as a Service



Popular SaaS offering types include email and collaboration, customer relationship management, and healthcare-related applications. Some large enterprises that are not traditionally thought of as software vendors have started building SaaS as an additional source of revenue in order to gain a competitive advantage.

SaaS Examples: Google Gmail, Microsoft 365, Salesforce, Citrix GoToMeeting, Cisco WebEx
Common SaaS Use-Case: Replacing traditional on-device software
Technology Analyst Examples: Bill Pray (Gartner), Amy DeMartine (Forrester)

PaaS: Platform as a Service

Cloud platform services, or Platform as a Service (PaaS), are used for applications, and other development, while providing cloud components to software. What developers gain with PaaS is a framework they can build upon to develop or customize applications. PaaS makes the development, testing, and deployment of applications quick, simple, and cost-effective. With this technology, enterprise operations, or a third-party provider, can manage OSes, virtualization, servers, storage, networking, and the PaaS software itself. Developers, however, manage the applications.

Enterprise PaaS provides line-of-business software developers a self-service portal for managing computing infrastructure from centralized IT operations and the platforms that are installed on top of the hardware. The enterprise PaaS can be delivered through a hybrid model that uses both public IaaS and on-premise infrastructure or as a pure private PaaS that only uses the latter.

Similar to the way in which you might create macros in Excel, PaaS allows you to create applications using software components that are built into the PaaS (middleware). Applications using PaaS inherit cloud characteristic such as scalability, high-availability, multi-tenancy, SaaS enablement, and more. Enterprises benefit from PaaS because it reduces the amount of coding necessary, automates business policy, and helps migrate apps to hybrid model. For the needs of enterprises and other organizations, Apprenda is one provider of a private cloud PaaS for .NET and Java.

IaaS: Infrastructure as a Service

Cloud infrastructure services, known as Infrastructure as a Service (IaaS), are self-service models for accessing, monitoring, and managing remote data center infrastructures, such as compute (virtualized or bare mental), storage, networking, and networking services (e.g. firewalls). Instead of having to purchase hardware outright, users can purchase IaaS based on consumption, similar to electricity or other utility billing.

Compared to SaaS and PaaS, IaaS users are responsible for managing applications, data, runtime, middleware and OSes. Providers still manage virtualization, servers, hard drives, storage, and networking. Many IaaS providers now offer databases, messaging queues, and other services above the virtualization layer as well. Some tech analysts draw a distinction here and use the IaaS+ moniker for these other options. What users gain with IaaS is infrastructure on top of which they can install any required platform. Users are responsible for updating these if new versions are released.

IaaS Examples: Amazon Web Service (AWS), Microsoft Azure, Google Compute Engine (GCE)
Common IaaS Use-Case: Extending current data center infrastructure for temporary workloads

Being overqualified and unmanageable for that job or position you are interviewing for

I have had one too many interviews where I was an ideal fit for the job technology-wise, but not so much what the interviewer, usually a director, technical manager, VP or CTO, was looking for, team-wise. Not because I'm not a team player. Not because I'm not a great guy, friendly or easy to work with. Heck, I am very even tempered and truly believe in a constructive team environment. No, they didn't like me because I had too much expertise, not only in technology but in overall experience, and specifically in managing and dealing with people. I'm not trying to toot my own horn here. Facts are facts. My real resume is about 14 pages long. I have a very wide breadth of knowledge and experience that I've worked hard over the last 20 years to have.

In an interview, I can come off as too confident. I come off very relaxed, because I am. I don't fear interviewers or speaking in front of audiences and I respect people, not positions. By this I mean, you could put the president of the United States in front of me and it wouldn't make me timid in the least, especially if I was not a fan. This ability to stay relaxed and actually enjoy an interview can be taken very negatively. It can come off as aloof or disinterested, because if I really cared, why wouldn't I be on the edge of my seat, biting my nails or saying please, please, please. I just don't work that way. I'm not cocky, I'm confident. I know the value I bring to the table. I know this, because I work very hard every single day. I know this, because I wake up every single morning and ask myself, what can I do today to make me a better person? But I also have to remember that people cannot read my mind and do not know me. I have to put myself in their shoes and I have to try and understand what they're "really" looking for when it comes to their perfect hire. 99% of the time they're looking for someone who is diplomatic, who listens, who takes direction without bitching and who is positive. I don't care how technical you are, if you don't have these qualities and it shows, you just won't get the job.

Unfortunately for some, including myself, interviewers are also looking for someone who is not smarter than they are or at least someone who doesn't trump their experience. If you do, then you're creating a job security fear or a work rivalry fear in the mind of the interviewer. This was and still is a very important lesson I've learned that gets thrown in my face every time I don't keep tabs on myself. Self awareness, honesty with oneself and the constant practice of introspection are all key.

An example: 99% of people in this world act out of fear or some gradation there of. In order to best understand people, you have to understand their fears, their insecurities and somehow get a glimpse into their self-esteem. If someone has a low self-esteem, it is very likely they are emotionally sensitive. If they are sensitive to what others say, that joke you just told could be a serious turn-off to them because they are in no state of mind to "hear" the joke. They put everything you say in the context of "Is this person saying something that might be infringing on my insecurities?". In other words, when you are insecure, you are always looking at what people say in the context of, is this an insult to me.

Another example: Ones standards are a reflection of what is going on inside their head. And since we cannot read peoples minds, we have to infer as best we can from what we can see. In some cases, it is pretty easy to see what kind of standards people have because they wear it on the outside. The body we have and the way we carry ourselves is a reflection of our physical standards. If you're overweight, you smell, you look disheveled, if you dress poorly, if you're not self-aware of how you look when going into an interview than you're telling the other people around you that you lack a good physical standard by which you live your life. Believe me, you are telling them quite a bit more than this but let's stay on point. If the person interviewing you looks like this, then you need to understand, they lack a good physical standard or it is an extremely low priority for them. That being the case, you can probably surmise that it might be best not to talk about the fact that you workout or run a lot because that will most likely be a turn off to them. When you talk about this, you are just reminding them what they are not and don't have time to be or at least haven't made time for and believe me, they will not want you around on a daily basis making them feel bad.

I urge you to size up your interviewer immediately upon entering the interview.

Here are some tips.

1) Don't give them an excuse.

Make sure you have shaved, you're wearing business attire, you've showered, you are fresh, not hung over or tired or god knows what else.

2) Get a feel for the personality types that are interviewing you.

I was recently in an interview with 2 interviewers one of which was a director and the other the technical manager, bot of which I had way more depth of experience than. This was readily apparent early on in the interview. The technical manager was a very nice guy, timid and more of a home programmer type than Enterprise level i.e. a crank the code out and don't worry about anything else.

I was a perfect fit for the position. Technically and from a managerial perspective had a much more extensive knowledge base to work from. However, I made the mistake of over-selling myself.

This is a problem when you have guys that have been with the company for years and don't want to be out-shined by someone coming in, especially in a smaller environment where it would be extremely obvious that someone knows more than you. They want to stay in control and that is extremely hard to do when its obvious you know more than they do. People will start to lose respect for them and they know it. Knowledge and experience is power.

Because of this and because of their fear that you will outshine them, they will chalk it up to you not being "manageable". Even though you can get 400% more work done then anyone there and they don't have to pay you a dime more money than what was originally offered, your expertise and experience will be your downfall. And to restate that a slightly different way, the way you project your expertise will be your downfall. You could be the world's foremost expert on something and if you are perceived as non-threatening you may just win the battle. Do not allow absolute visibility into all you have to offer, it will behoove you in the end. Sometimes transparency is a bad thing.

3) Don't feel so comfortable in an interview that you believe you can be fully transparent. 

The less information you have to give in order to get the job the better.

4) Don't talk about your personal hobbies and what you do in your free time. 

For example, I am a runner. 99% of people either don't care about running or flat out hate it. For me to talk about running and be excited about it is just showing them that I have other things to occupy of distract my time away from getting work done.

To talk about a number of things you have going on in your personal life will be seen as possibly spreading yourself way too thin which can also be a huge turn off.  Telling them you your kids little league coach, you run and also teach fitness classes, you are a writer and write books, you have your own soap business on the side are all things you do not want to talk about.

5) Don't project yourself as being more than the position needs you to be!

People don't want a go getter for positions under Vice President, they want someone they can "handle", someone they can "manage" and someone who will do what they command. They want you to make there life easy for them, nothing more. It doesn't matter if you would be a great fir for the company and their bottom line, what matters is that you are easily manageable by the person who is interviewing you. If you cannot get past him, nothing else matters.

6) Know your role

This may sound obvious but if you are a god interviewing for a position of peon, don't put your god face on in the interview. Isn't it obvious that they won't want you? They will wonder why you are interviewing in the first place. They will think that you might just be hard up and two seconds after they hire you, someone else will offer you a better position and you will leave. On the same note, if you are applying for peon, your resume must be written in such a way to project your experience as aligned with being a peon.

7) Do not intimidate them

Most of you probably don't even know you're doing it. Most of you think that you're just trying to show the interviewer your "value" but I guarantee some of you take it too far. I know I did. Stick to the needs of the job at hand. Do not go off on tangents that could serve to harm the impression someone has of you. Sometimes the enemy of good is better. Don't volunteer more information just because "you" think it sounds great. More information means more opportunity to turn someone off especially if you're already qualified enough for a position. Do not oversell yourself and do not project your experience in such a way as to say "Hey, look at me, I'm awesome and you don't compare.".

** Check back for more on this.

How do you use your Google Drive content in a website, email or custom viewer without the Google viewer displaying it? I'll show you

A lot of people have a Google Drive account and if you don't I highly recommend you get a gmail account and get one.

It is pretty awesome what it can do and I have even upgraded my account too 100 GB for just $1.99 per month. It is invaluable and allows you to access to every file you store from any device, anywhere in the world. It allows you to share files and folders, collaborate on documents or spreadsheets, it has built in version control (to some degree) and at the time of this writing, they give you 15 GB of storage for free. (I make no money or have any affiliation with Google Drive.)

Recently, I wanted to try and use some of the content I had in my Google Drive folder on a website of mine because I didn't want multiple copies of the same file all over the place. I like to be able to update my content in 1 place and have 1 source of the truth so to speak. So to figure out the answer, I read a bunch of blogs, looked at YouTube videos, which turned out to be bogus, and read articles on how to do it, all to no avail. The solutions they proposed may have worked at one time, but Google must have found the hole and covered it up. Always best to know what you can and cannot do when using Google Drive. Google Terms Of Service

There are easy ways of finding out what the proper URL is in order to bypass the Google viewer are. You could simply hook up fiddler and click the download button when viewing your Google Drive content and you would see the redirect to a URL that is meant to deliver only your content.

To make it easy, I am going to just share with you the URL and what you need to do to view your content without the Google viewer wrapper.

When you share content on Google the normal URL looks like this:

The important part if the unique id assigned to the file in that URL. The unique id in that URL is: 0A9Iwe-rgtO-POmQASDlLajlkb32

So now we will use a different URL which is used to download the content and thereby bypassing the Google viewer to view it.

Note that you can use SSL or not, it's up to you (i.e. use http or https)

Questions this post answers:
How to view content on Google Drive without viewer
View Google doc by itself
View Google doc without viewer
google doc viewer api
view Google docs directly in chrome
view Google docs directly in ie

Let's take a look at what the term deep linking refers to

In the context of the World Wide Web, deep linking consists of using a hyperlink that links to a specific, generally searchable or indexed, piece of web content on a website (i.e., rather than the home page (i.e.

This link: is an example of a deep link. The URL contains all the information needed to point to a particular item, in this case the why section of the MSN article on retiring, instead of the MSN home page at

A mobile deeplink functions much like a traditional hyperlink on a webpage. It is composed of separate elements that make up what is referred to as a Uniform Resource Identifier (URI). The URI contains all the information that, for example, might launch a mobile application to a specific screen.
When thinking about deeplink structure, the best practice is to implement a URL with a unique scheme name and routing parameters (path and query strings) that represent custom actions to take in the app.

Mobile deeplinking is especially useful for promotional efforts because it allows you and any third party to open the mobile app when a link is clicked, rather than driving to a website or to your app’s listing on the iOS App Store or Google Play.

Another example of deep linking allows application developers to link to specific pages or screens within the NY Times mobile application, a specific story lets say.

For desktop applications, we could use URL's to open an application as well as direct the application to go directly to a specific screen when the link is clicked.


Why some websites don't like it and the legal ramifications of doing it




Probably the earliest legal case arising out of deep-linking was the 1996 Scottish case of The Shetland Times vs The Shetland News where the Times accused the News of appropriating stories on the Times' website as its own.


In December 2006, a Texas court ruled that linking by a motocross website to videos on a Texas-based motocross video production website did not constitute fair use. The court subsequently issued an injunction. This case, SFX Motor Sports Inc., v. Davis, was not published in official reports, but is available at 2006 WL 3616983.


What about websites that use Adobe Flash and AJAX?

Websites which are built on web technologies such as Adobe Flash and AJAX often do not support deep linking. This can result in usability problems for people visiting such websites. For example, visitors to these websites may be unable to save bookmarks to individual pages or states of the site, web browser forward and back buttons may not work as expected, and use of the browser's refresh button may return the user to the initial page.

However, this is not a fundamental limitation of these technologies. Well-known techniques, and libraries such as SWFAddress and unFocus History Keeper, now exist that website creators using Flash or AJAX can use to provide deep linking to pages within their sites.

What is it you actually say when asked "Why should we hire you?" in an interview? If you are not prepared to answer this question, then be prepared not to get the job.

I'm asked this question quite a bit in interviews and I think most interviewers are shocked by the fact that I have a deep understanding of what I bring to the table along with being well versed at defining myself and singing my own praises.

This is something I have worked on time and time again over the years. And while I may not be for everyone, when you are considering potential candidates, I would hire me over the next guy every single day of the week and twice on Sunday. I say this not because I think I'm smarter than the next person or even because I believe I know something they don't. I say it because I work hard every single day of my life. I say it because I also work smart. I have done this my entire life and will continue to do so until my very last breath. I do this, because this is who I am, period.

Instead of trying to explain the things you should convey when asked this question in an interview, I'm going to show you what I say. I urge you to take the time and write down the top 10 reasons "why" someone should hire you. You must write it down in order to best provide a fluidity of mind when rattling so much information off at one time. I'm not proposing you say as much as I have written below. What I am saying is, get to know yourself. The more you understand who you are at this point in your life, the easier it will be to convey that understanding to others (in brevity). You might be surprised at what you come up with. A last note: Be honest about how you see yourself. Find those things that you can be positive about without making things up. If you're having a hard time coming up with something, you may just be in a negative frame of mind. Walk away and think about it for awhile and then come back later to write it down when it comes to you. I always find a certain type of music or certain themes of video on youtube help me to get into a frame of mind in which I'm positive and feel good about the world. This usually helps me when I write.

My Top 10 Reasons Why You Should Hire Me

#10 I have midwest ethics and a deep understanding of professional integrity

I'm originally from Wisconsin. If you've ever heard that people from the midwest, especially Wisconsin, are the friendliest people on Earth, then you've heard correctly. I say this without pride or prejudice, it just happens to be fact. With midwestern values comes professional integrity.  I would be willing to bet that most people would falter at even defining what professional integrity is, so let me take a moment to define it.

Professional Integrity DefinedA professional is one who willingly "adopts" and consistently applies the knowledge, skills, and values of a chosen profession. Integrity may be the most appropriate word used to describe the person who willingly and consistently acts in accordance with social standards or moral values of society. Professional integrity thus defines the professional who consistently and willingly practices within the guidelines of the mission of a chosen profession under the obligation of a Code of Ethics.

#9 I am tenacious

I have been tenacious my entire life. When I go into something, I go in with all of my force. I am passionate and tenacious about what I do because I love to do it. I come with a force of mind and a determination that I rarely see matched. I'm built this way. I will always be this way and am truly thankful for having this trait. My mother was the same way. A medical doctor, author and mother of six children. A physician and professor highly regarded as being a paragon in her field. She had a work ethic like no other and an endurance that is unmatched.

My tenacity is only matched by my resourcefulness. I pride myself in and have spent a lifetime learning how to learn. This is a skill everyone has but few people ever focus on. It is not always what you learn that makes the difference. Sometimes it is ones ability to learn and to learn expeditiously that can make or break a situation, especially one that is time sensitive. If I don't know something that I need to know, you can bet everything you have, go all in, double down and then some that I will figure it out one way or another.

#8 I am free from distraction

I am not married nor do I have children. I am very certain I will be married one day and I may have children as well, but for now I have neither. I devote my time to learning and becoming a smarter, more efficient person every single moment of every single day. I have learned the art of single-mindedness, which is one of the most valuable skills to have when working toward reaching a goal. I work on my ability to focus my attention on the important things in life. I work on my ability to ignore the things that are not important as well. These are 2 different skills that are extremely valuable in being successful at any endeavor.

#7 I have made a TON of mistakes.

How could making mistakes constantly be a good thing? Because I rise to the challenge every single day. I make mistakes, because I push myself to do things that are outside of my comfort zone and outside of my skill set in order to grow. I challenge myself to do the things that do not come easy to me and in so doing I master that which was once a weakness.  I carry with me a healthy curiosity and am un-phased by the threat of failure. I would put forth that a life lived without failure is a life poorly lived. Because if you haven't failed in life, you have not pushed yourself to do things outside of your means, which is the only true path of constant growth.

I learn from my mistakes. I may not learn the first time or the second time, but I will keep trying until I find a way. And if I don't find a way, I will make a way. Mistakes can be very painful, plain and simple. Pain and fear of failure are the two biggest reasons, in my opinion, why most people stay confined to a path of least resistance in life. And with each mistake I make, I ask myself one very important question: Am I going through this pain or am I growing through it? This serves me well. It serves to focus my mind to better look at the situation I'm going through with greater clarity and with an intention to not only solve the problem but to learn from the experience.

I would personally be more apt to follow the person who has a greater experience with life, earmarked by massive trial and error, than one who has lived a shallow existence. The person who knows what "not" to do, because they have had that experience.

#6 I have a breadth of experience that is second to none

I've been a contractor for most of my adult life. I have done this specifically because I wanted to work in multiple industries and learn from as many people as possible. I was a jack of all trades and a master of none for quite a few years. This process was invaluable in the quantity and quality of what I learned. Those that have been with the same company usually learned a single way of doing something that may have been right at the time, but that time has passed and they never bothered to learn different ways of doing things. Most haven't had exposure to other ways of doing things and are often set in their ways, mainly because they're older and have other life responsibilities. Doing your job, taking care of your family and trying to learn new things is more than most people can handle. Most are resistant to even try something new for fear that once started, there will be no end to the amount of time and effort they will have to put forth to fully figure out a new concept or paradigm.

I would rather have a multiplicity of perspectives to work from when trying to solve problems. Think of it as a mental tool shed and I have accumulated a massive amount of different tools to work with in order to solve issues that come up. I have learned to work with people because it was the only way to survive as a contractor. This is a skill that is lost when working in a safe environment. If we don't use it, we lose it.

#5 I understand didactic communication and the notion of a team environment

Communication in this day and age is so very key when working in a team environment. Environments that are overly political must be navigated through with the utmost diplomacy while still being assertive and doing ones job. The ability to teach others and be taught is invaluable. The ability to explain subject matter in a way that is clear and concise is not only celebrated but worshiped. Some of the most successful people in life are so because they have learned the art of communication and can mobilize others to their cause.

It is rare that one works totally on their own. We rely on others to help our cause. You must learn the art of communication, have a self-awareness of how you are perceived and try to keep those around you in a positive frame of mind.  No one wants to work with someone who is negative or complains about every single decision made. No one wants to work with someone who is overly aggressive or has a bad attitude in general. You must be willing to lead and learn at the same time.  The best environments are those that promote learning without fear of reprisal and without fear of being made fun of. Work will always be work, but those that understand that it is the people that make the job are the ones that are the happiest with their job and their life in general.

#4 I practice what I preach

I preach excellence. I preach a never say "die" attitude. I preach finding a way or making a way. I preach that success does not require you to look out the window, it only requires you look in the mirror. I preach that only those who are willing to risk going too far, will ever possibly know, how far one can go. I preach these things because I live by them ever single day.

I preach to be kind to others. I preach to treat others how you want to be treated. I preach that the single greatest way to live a full and complete life is to have purpose. I preach nutrition. I preach that taking care of yourself, mind, body and spirit is the only way to live. I have learned hard lessons in my life and I have made it through each and every trial and tribulation I have ever come across. I'm still here after all. I'm here to build people up, not put them down. Constructive competition is healthy and creates environments where everyone learns and everyone grows.

I practice what I preach because I only preach to others those things I truly believe in. And when I believe in something, I follow it. You will never truly understand the full beauty and power life has to offer until you live a life in which your actions are congruent with your thoughts.  It has taken me a long time to learn this concept and I practice the art of introspection every single day.

#3 I am honest and trustworthy

You are only as good as your word. This is as true in business as it is in life. What goes around, comes around. In life, you get what give and I've been blessed with that understanding my entire life. It's too commonplace to run across people who are only out for themselves. Who have lost their way when it comes to understanding that the quality of your life is directly proportional to the affect you have on others. When we help others, we help ourselves. And no matter what happens to me and who I run across that may not have the same code of ethics I do, I will not falter in how I treat others, because I know who I am. If you can say that about yourself, if you can say "I truly know who I am", than you are light years ahead of the majority.

#2 I play to win

Constructive competition. A term I learned well growing up in a family of 6 siblings where I was the youngest by a long shot. The next oldest has 7 years on me. They are all competitive in their own right and in order to keep up, I had to compete against the odds. I took that challenge and that is not to say I won many battles early on, but I learned how to fight and eventually how to win. I also learned how to learn, which is the single most important skill any human being can have. There has come many a day where the sun has shined down on me in victory because of it.

I play to win in all aspects of my life, including business. I want to know more than you. I want to be smarter than you. I want to win every single conversation I have with you. I do this, not so I can put it in your face or put you down. It truly has nothing to do with you. I do this because I want to be the best person I can be and I use others as a gauge in order to determine what areas in my life, I am lacking in. If I don't understand where my weaknesses are, I will never be able to fix them.

I'm not looking to be perfect in the end. I'm looking to have a smile on my face when I take my last breath and leave this place, because I know, I did everything I possibly could to be the best person I could be. I took nothing and no one for granted. I fought the good fight. I left this world a better place, however infinitesimally small and had a positive impact on those I came into contact with. I want to leave this place with a confidence that there wasn't one more thing I could have done. And while I may not reach that point entirely, it will not stop me from trying.

#1 My life is a blessing

I can honestly say that I have surrounded myself with truly fantastic people. "Birds of a feather" is a powerful concept and a guiding principle in my life. When you find yourself surrounded by losers and by flakes, you know who you are. I surround myself with extraordinary people and with those on the same mission as me.

I am extremely happy. Not a delusional happy but a solid reaffirming happy that can only be gained through growth. Through trials and errors. Through travel across many bumpy roads and heavy winds. I look back on my life and am truly thankful for going through what I've gone through. I say this because I'm so very happy with where I am now and with who I am now. And even though I've had to learn many a lesson the hard way, I understand that I probably needed to go through what I went through in order to be where I am.

I think Einstein said it best, "There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.". We are given this choice and I truly believe that everything in life is a miracle.

So the question is, which person would you rather surround yourself with, because make no mistake, you aren't just hiring for a position. You are hiring someone who will be a large part of your life, seeing as work, for most of us, is life consuming.

Surround yourself with those on the same mission as you.

One of the C#'s little hidden gems. If you want to stump your co-workers in C# trivia, than let me introduce you to deferred execution.

So you may or may not have ever heard the term "deferred execution", but I am willing to bet the latter is the most true, for the majority of you. It is also likely that the majority of you use LINQ in your application code, but never really delved deep into how LINQ works below the surface.

Every so often I will come into an interview in which I am asked what deferred execution is, albeit not outright. I am usually given an example on a whiteboard and asked to solve for a specific variable. Their is an intuitive answer that is simple and right in your face, but that is the trick, because that is not the "right" answer. The right answer has to do with deferred execution and when LINQ processes or iterates its queries.

In the simplest of definitions, deferred execution means that the evaluation of an expression is delayed until its realized value is actually required. Deferred execution can greatly improve performance when you have to manipulate large data collections, especially in programs that contain a series of chained queries or manipulations. In the best case, deferred execution enables only a single iteration through the source collection.

The LINQ technologies make extensive use of deferred execution in both the members of core System.Linq classes and in the extension methods in the various LINQ namespaces, such as System.Xml.Linq.Extensions.

Deferred execution is supported directly in the C# language by the yield keyword (in the form of the yield-return statement) when used within an iterator block. Such an iterator must return a collection of type IEnumerator or IEnumerator<T> (or a derived type).

Deferred execution applies to all varieties of LINQ, including LINQ to SQL, LINQ to Objects and LINQ to XML. However, of the three, it is only LINQ to SQL that returns an expression tree by default. Or more specifically, it returns an instance of the IQueryable interface that references an expression tree. A query that returns IEnumerable still supports deferred execution, but at least some larger portion of the result is likely to have been generated than is the case with LINQ to SQL. In other words, all types of LINQ support deferred execution, but LINQ to SQL supports it more fully than LINQ to Objects or LINQ to XML.

This topic shows how deferred execution and lazy evaluation affect the execution of your LINQ to XML queries.


The following example shows the order of execution when using an extension method that uses deferred execution. The example declares an array of three strings. It then iterates through the collection returned by ConvertCollectionToUpperCase.

public static class LocalExtensions
    public static IEnumerable<string>
      ConvertCollectionToUpperCase(this IEnumerable<string> source)
        foreach (string str in source)
            Console.WriteLine("ToUpper: source {0}", str);
            yield return str.ToUpper();

class Program
    static void Main(string[] args)
        string[] stringArray = { "abc", "def", "ghi" };

        var q = from str in stringArray.ConvertCollectionToUpperCase()
                select str;

        foreach (string str in q)
            Console.WriteLine("Main: str {0}", str);

This example produces the following output:
ToUpper: source abc
Main: str ABC
ToUpper: source def
Main: str DEF
ToUpper: source ghi
Main: str GHI

Notice that when iterating through the collection returned by ConvertCollectionToUpperCase, each item is retrieved from the source string array and converted to uppercase before the next item is retrieved from the source string array.

You can see that the entire array of strings is not converted to uppercase before each item in the returned collection is processed in the foreach loop in Main.


At this point, it is important that you understand the semantic difference between the terms "Eager" vs. "Lazy Evaluation" as well, because it applies to this topic.

Eager vs. Lazy Evaluation

When you write a method that implements deferred execution, you also have to decide whether to implement the method using lazy evaluation or eager evaluation.
  • In lazy evaluation, a single element of the source collection is processed during each call to the iterator. This is the typical way in which iterators are implemented.
  • In eager evaluation, the first call to the iterator will result in the entire collection being processed. A temporary copy of the source collection might also be required. For example, the OrderBy method has to sort the entire collection before it returns the first element.
Lazy evaluation usually yields better performance because it distributes overhead processing evenly throughout the evaluation of the collection and minimizes the use of temporary data. Of course, for some operations, there is no other option than to materialize intermediate results.

Have a fun time stumping your co-workers the next time they want to make it seem like they know more than you when it comes to programming in C#!

The top 10 things you really should be doing to have the best self-confidence in an interview

I have been told by people time and time again, that the reason they lost the interview was because they didn't project enough self-confidence in an interview and the interviewer lost faith that they could survive in their environment. The industries where people have the greatest self-confidence problems when interviewing are the ones in which they are expected to know very technical and specific information. Engineers are rank with those who have issues with self-confidence and self-esteem, because it is a very dog eat dog environment and they know that competition will weed out the incompetent fast.

Throughout the majority of my professional life, I have seen it first hand, because I have interviewed many who by the very site of them, can be perceived as lacking the necessary self-confidence that one looks for in order to fill a technical position. I have had people literally break down in tears in front of me. A terrible site to see.

Most people have learned to lack confidence in their abilities, be nervous when addressing others, or be anxious when all the attention is on them. They have learned this from their relationships with their parents, their peers or from being let loose in a world where people do not build other people up, they beat them down, in an attempt to gain control. We remember past failures. We second-guess ourselves. And, unfortunately, our learned lack of self-confidence is harmful to us at the most important times in our life, like interviewing for a job you want and need.

To make matters worse, research shows that, on average, interviewers reach final decisions about applicants in only four minutes after meeting them. In this time, there is little more to evaluate than how you look and speak, how you carry yourself, and how you greeted the interviewer, all clear clues of your level of self-confidence.

Being confident from the moment you walk through the door will always give you a better chance of landing the job. The good news is that self-confidence can be generated and regained. Here’s how:

1) Be Prepared

Being prepared is the number 1 reason why people fail in technical interviews or interviews in general. Self-confidence is generally a reflection of how prepared you feel you are, not just for technical interviews, but for anything in life. Our mind plays tricks on us and unless you are a seasoned bullshit artist, will not allow you to come off as something you are not i.e. confident when you know that you don't know, anything. Being prepared will make or break 99% of your interviews and I urge you to take the time to know the company, know the interviewer and know the materials you are going to be interviewed on ahead of time. Companies have a website, people usually have a profile on linkedin, facebook, twitter or any number of other social media websites. And it should be a no brainer that you need to understand the subject you are being interviewed for ahead of time which is always in the original job description.

2) Power Posing

A great video to watch is Amy Cuddy’s, "Your Body Language Shapes Who You Are", where she asserts that not only does body language affect how others see you, but how we see ourselves. Her studies show that “power posing” – standing in a posture of confidence, even when you don’t feel confident – affects your brain’s testosterone and cortisol levels, and makes you feel more confident. Her research concludes that changing your body positions does influence how others see you and even alters your body chemistry.

Power Posing before an interview – or before any event where you are in need of a confidence boost – will greatly improve how you feel and appear to others.

3) Catch More Flies With Honey - Be Attractive

In a Radford University publication, Behavioral Interviews: "It’s Not What You Know, It’s What You Did", confidence is strongly correlated to attractiveness. Multiple studies also conclude that “attractive” job candidates get more offers and make more money. Making yourself attractive during an interview with a comfortably firm handshake, direct eye contact, good posture, relaxed but passionate communication style, and a genuine smile will give you an edge over other candidates. No matter what you look like, you can do and say things that will make you attractive to others. Be more self-aware of what you're doing in an interview and take notes on what things you do that seem to get a good response from people. This can be done in or outside an interview.

My best tip? Practice mock interviews using your web cam or video recording camera and play back the video so you can see what others see! This is invaluable for me. I look totally different in reality than how I see myself in my own head. I do things that are odd that I was never aware of because I could not see myself. It will all come out on camera.

4) Body Posture

You can naturally adjust your body for confidence by asking, “If I was really interested in what my interviewer was saying, how would I sit?” You will be surprised how often you need to readjust your body and how much more confident you feel afterwards. Current scientific studies show the impact body language had on the hormones within the body. High power poses increased testosterone by 20 percent and decreased cortisol levels by 25 percent. It is amazing how much hormone levels play in how you are perceived as well as how you look, including body posture.

Tip: Do not drink alcohol up to 48 hours before an interview. Stay away from foods and beverages that affect blood sugar levels. Alcohol reduces testosterone levels for up to 24 hours after just 1 drink in men. Foods and beverages that affect your blood sugar will cause fluctuations in your energy levels and sabotage your ability to recall information as well as cause posture issues. Smoking "causes" anxiety, it does not relieve it, and because of this, can affect body posture, cause fidgeting and is truly something no interviewer wants to smell while sitting in a small poorly ventilated room with you.

5) Affective Memory

Affective Memory is a central part of Method Acting process, a system pioneered by the late Russian theatre director and actor, Constantin Stanislavski, which requires actors to call on personal memory details from a similar situation to those of their characters. Used with positive personal experiences, this same technique can be effectively applied to rehearsals for job interviews, especially when rehearsing for the critical first four minutes.

Close your eyes. Recall and experience a time you gave a firm and confident handshake. See the eyes and face of a friendly and kind person you know or interviewed with before. Hear their reassuring words. Feel the energy of a positive and successful interview, meeting, or exchange you had in the past. Pay attention to what your posture, breathing, and heartbeat were like. Rehearse and experience this interview in your head, heart, and hands – live it.

Done completely, this exercise will give you confidence for your upcoming interview by connecting it to positive and successful experiences you have already had in your life. You will no longer be walking into an unknown and perhaps scary circumstance, but one you have successfully already experienced. In fact, if done correctly, your mind will not be able to distinguish the difference between the two.

6) Practice, Practice, Practice

As you grow in your career, knowledge, and expertise and have more successes in life, you will naturally become more confident when interviewing. Experience and confidence usually go hand in hand.

If you are early in your career or short on the experience, knowledge, or successes you need to feel fully confident for the job you are interviewing for, seek assistance from relevant books, the web, training courses, and a mentor. Good resources and a commitment to study will give you all the confidence you need.

7) Dress The Part And For god Sake - Shower

Dressing appropriately for interviews is extremely helpful. When you look good, you feel good and when you feel good, you come off as more self-confident. Use perfumes or colognes sparingly. Just because you like it, doesn't mean someone else will. Smell can turn someone off in a heartbeat and you wouldn't want to be denied a job because someone was annoyed by how you smell. It happens! For that matter, be sure you are clean and showered. I have interviewed several people that have come in with greasy hair, disheveled and that smell like they haven't showered in days. If you are a smoker, then this is an even bigger problem for you. Get clean and shower right before you go into an interview.

8) A Positive Focus Is Key

We tend to focus our energies on the negative things that happen to us. Despite buckets full of positive experiences, it only takes one or two nasty comments to knock someone off their horse. In fact, meanness is at the root of all confidence issues. Being laughed at when you make a mistake, being harshly rejected by someone you like, or being taunted on a schoolyard all play a part in a person’s self-confidence. To overcome negative experiences in life, focus on positive ones. Most people can count only a few really bad experiences in life, while positive ones are abundant.

Even better, extend this positivity to others. Dr. Maya Angelou once said, “At the end of the day people won’t remember what you said or did, they will remember how you made them feel.” We have the ability to give the gift of confidence to everyone we meet by being constructive and kind in all our interactions. I encourage you to be a champion of confidence for others. It not only feels good and helps others, but gives you greater confidence as well.

9) Ignore The Critic

You are the biggest critic of  you! You must learn to ignore the critic within. There is an old African proverb, "If there is no enemy within, the enemy outside can do us no harm". On the same subject, there are certain things that will trigger the critic to start knocking your self-confidence down. What are your low confidence triggers when interviewing? (e.g., entering the building, shaking hands with your interviewer, sitting down to start the interview, starting to speak, answering questions) Write them down now. Then write down what you say to yourself when these events occur and how it makes you feel. Cross out any negative “self-talk” and re-write the statements in a positive and assertive manner – a way that makes you feel confident and good about yourself when you read and say them. Turn, “I will never get this job” into “I am the best person for this job. This company needs me.”

By re-writing your self-talk, you will change the way you feel and how you behave. Negative self-talk will generate low self-confidence and self-esteem issues while positive self-talk produces the opposite effect. Practice positive self-talk throughout your life and your confidence levels will soar.

10) Be Aware and Be Present

The key to confidence when interviewing is coming prepared and staying present, connected and fully engaged in the process and what you need to convey about yourself. Connect with your interviewer by providing helpful answers to questions and being actively interested in what they have to say. The more focused you are on what you trying to accomplish; the less room insecurities, nervousness, and self-doubt will have to creep in.

If you use REST, I'll bet you don't know what the 6 constraints of the REST architecture are?


So many programmers use REST without fully understanding its principles as well as its constraints. Here I'll give you a brief overview of the 6 constraints REST is bound by.

The six constraints of the REST architecture are:

1) Uniform Interface

The uniform interface constraint defines the interface between clients and servers. It simplifies and decouples the architecture, which enables each part to evolve independently. The four guiding principles of the uniform interface are:

a) Resource-Based

Individual resources are identified in requests using URIs as resource identifiers. The resources themselves are conceptually separate from the representations that are returned to the client. For example, the server does not send its database, but rather, some HTML, XML or JSON that represents some database records expressed, for instance, in Finnish and encoded in UTF-8, depending on the details of the request and the server implementation.

b) Manipulation of Resources Through Representations


c) Self-descriptive Messages

Each message includes enough information to describe how to process the message. For example, which parser to invoke may be specified by an Internet media type (previously known as a MIME type). Responses also explicitly indicate their cache-ability.

d) Hypermedia as the Engine of Application State (HATEOAS)

Clients deliver state via body contents, query-string parameters, request headers and the requested URI (the resource name). Services deliver state to clients via body content, response codes, and response headers. This is technically referred-to as hypermedia (or hyperlinks within hypertext).

Aside from the description above, HATEOS also means that, where necessary, links are contained in the returned body (or headers) to supply the URI for retrieval of the object itself or related objects. We'll talk about this in more detail later.

The uniform interface that any REST services must provide is fundamental to its design.

2) Stateless

As REST is an acronym for REpresentational State Transfer, statelessness is key. Essentially, what this means is that the necessary state to handle the request is contained within the request itself, whether as part of the URI, query-string parameters, body, or headers. The URI uniquely identifies the resource and the body contains the state (or state change) of that resource. Then after the server does it's processing, the appropriate state, or the piece(s) of state that matter, are communicated back to the client via headers, status and response body.

Most of us who have been in the industry for a while are accustomed to programming within a container which provides us with the concept of “session” which maintains state across multiple HTTP requests. In REST, the client must include all information for the server to fulfill the request, resending state as necessary if that state must span multiple requests. Statelessness enables greater scalability since the server does not have to maintain, update or communicate that session state. Additionally, load balancers don't have to worry about session affinity for stateless systems.

So what's the difference between state and a resource? State, or application state, is that which the server cares about to fulfill a request—data necessary for the current session or request. A resource, or resource state, is the data that defines the resource representation—the data stored in the database, for instance. Consider application state to be data that could vary by client, and per request. Resource state, on the other hand, is constant across every client who requests it.

Ever had back-button issues with a web application where it went AWOL at a certain point because it expected you to do things in a certain order? That's because it violated the statelessness principle. There are cases that don't honor the statelessness principle, such as three-legged OAuth, API call rate limiting, etc. However, make every effort to ensure that application state doesn't span multiple requests of your service(s).

3) Cacheable

As on the World Wide Web, clients can cache responses. Responses must therefore, implicitly or explicitly, define themselves as cacheable, or not, to prevent clients reusing stale or inappropriate data in response to further requests. Well-managed caching partially or completely eliminates some client–server interactions, further improving scalability and performance.

4) Client-Server

The uniform interface separates clients from servers. This separation of concerns means that, for example, clients are not concerned with data storage, which remains internal to each server, so that the portability of client code is improved. Servers are not concerned with the user interface or user state, so that servers can be simpler and more scalable. Servers and clients may also be replaced and developed independently, as long as the interface is not altered.

5) Layered System

A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way. Intermediary servers may improve system scalability by enabling load-balancing and by providing shared caches. Layers may also enforce security policies.

6) Code on Demand

Code-on-Demand (COD) is the only optional constraint in REST. It allows clients to improve its flexibility because in fact it is the server who decides how certain things will be done. For instance, with Code-On-Demand, a client can download a javascript, java applet or even a flash application in order to encrypt communication so servers are not aware of any encryption routines / keys used in this process.

However, using COD reduces visibility, which is why this constraint is optional. Also, not every API needs this kind of flexibility.

Do you even know what the Microsoft preferred C# Coding Conventions are?

The C# Language Specification does not define a coding standard. However, the following guidelines are used by Microsoft to develop samples and documentation, so you can bet they are a good place to start when learning C#.

Remember, these are not the "rules", they are guidelines, but in a world where there are many ways to skin the cat, so to speak, consistency and readability goes a long way in any environment in which you are not the only programmer. Give your fellow programmer and the company you work for, for that matter, the respect of doing your job correctly by writing readable and maintainable code. Those that follow coding conventions that are consistent are seen as much better programmers than those that do not.

Coding conventions serve the following purposes:
  • They create a consistent look to the code, so that readers can focus on content, not layout. 
  • They enable readers to understand the code more quickly by making assumptions based on previous experience.
  • They facilitate copying, changing, and maintaining the code. 
  • They demonstrate C# best practices.

Naming Conventions

  • In short examples that do not include using directives, use namespace qualifications. If you know that a namespace is imported by default in a project, you do not have to fully qualify the names from that namespace. Qualified names can be broken after a dot (.) if they are too long for a single line, as shown in the following example.

    var currentPerformanceCounterCategory = new System.Diagnostics.

  • You do not have to change the names of objects that were created by using the Visual Studio designer tools to make them fit other guidelines.

Layout Conventions

Good layout uses formatting to emphasize the structure of your code and to make the code easier to read. Microsoft examples and samples conform to the following conventions:
  • Use the default Code Editor settings (smart indenting, four-character indents, tabs saved as spaces). 
  • Write only one statement per line.
  • Write only one declaration per line.
  • If continuation lines are not indented automatically, indent them one tab stop (four spaces).
  • Add at least one blank line between method definitions and property definitions.
  • Use parentheses to make clauses in an expression apparent, as shown in the following code.

    if ((val1 > val2) && (val1 > val3))
        // Take appropriate action.

Commenting Conventions

  • Begin comment text with an uppercase letter.
  • End comment text with a period.
    // The following declaration creates a query. It does not run 
    // the query.
  • Do not create formatted blocks of asterisks around comments.

Language Guidelines

The following sections describe practices that the C# team follows to prepare code examples and samples.

String Data Type

  • Use the + operator to concatenate short strings, as shown in the following code.
    string displayName = nameList[n].LastName + ", " + nameList[n].FirstName;

  • To append strings in loops, especially when you are working with large amounts of text, use a StringBuilder object.

    var phrase = "lalalalalalalalalalalalalalalalalalalalalalalalalalalalalala";
    var manyPhrases = new StringBuilder();
    //Console.WriteLine("tra" + manyPhrases);

Implicitly Typed Local Variables

  • Use implicit typing for local variables when the type of the variable is obvious from the right side of the assignment, or when the precise type is not important.

    // When the type of a variable is clear from the context, use var  
    // in the declaration. 
    var var1 = "This is clearly a string.";
    var var2 = 27;
    var var3 = Convert.ToInt32(Console.ReadLine());


    // When the type of a variable is not clear from the context, use an 
    // explicit type. 
    int var4 = ExampleClass.ResultSoFar();


    // Naming the following variable inputInt is misleading.  
    // It is a string. 
    var inputInt = Console.ReadLine();
  • Avoid the use of var in place of dynamic.
  • Use implicit typing to determine the type of the loop variable in for and foreach loops.
  • The following example uses implicit typing in a for statement.

    var syllable = "ha";
    var laugh = "";
        laugh += syllable;
    The following example uses implicit typing in a foreach statement.

    foreach (var ch in laugh)
        if (ch == 'h')

Unsigned Data Type

  • In general, use int rather than unsigned types. The use of int is common throughout C#, and it is easier to interact with other libraries when you use int.


  • Use the concise syntax when you initialize arrays on the declaration line.

    // Preferred syntax. Note that you cannot use var here instead of string[]. 
    string[] vowels1 = { "a", "e", "i", "o", "u" };
    // If you use explicit instantiation, you can use var. 
    var vowels2 = new string[] { "a", "e", "i", "o", "u" };
    // If you specify an array size, you must initialize the elements one at a time. 
    var vowels3 = new string[5];
    vowels3[0] = "a";
    vowels3[1] = "e";
    // And so on.


  • Use the concise syntax to create instances of a delegate type.

    // First, in class Program, define the delegate type and a method that   
    // has a matching signature. 
    // Define the type. 
    public delegate void Del(string message);
    // Define a method that has a matching signature. 
    public static void DelMethod(string str)
        Console.WriteLine("DelMethod argument: {0}", str);

    // In the Main method, create an instance of Del. 
    // Preferred: Create an instance of Del by using condensed syntax.
    Del exampleDel2 = DelMethod;
    // The following declaration uses the full syntax.
    Del exampleDel1 = new Del(DelMethod);

try-catch and using Statements in Exception Handling

  • Use a try-catch statement for most exception handling.

    static string GetValueFromArray(string[] array, int index)
            return array[index];
        catch (System.IndexOutOfRangeException ex)
            Console.WriteLine("Index is out of range: {0}", index);
  • Simplify your code by using the C# using statement. If you have a try-finally statement in which the only code in the finally block is a call to the Dispose method, use a using statement instead.

    // This try-finally statement only calls Dispose in the finally block.
        byte charset = font1.GdiCharSet;
        if (font1 != null)
    // You can do the same thing with a using statement. 
    using (Font font2 = new Font("Arial", 10.0f))
        byte charset = font2.GdiCharSet;

&& and || Operators


    Console.Write("Enter a dividend: ");
    var dividend = Convert.ToInt32(Console.ReadLine());
    Console.Write("Enter a divisor: ");
    var divisor = Convert.ToInt32(Console.ReadLine());
    // a run-time error when divisor is 0. 

New Operator

  • Use the concise form of object instantiation, with implicit typing, as shown in the following declaration.
    var instance1 = new ExampleClass();
    The previous line is equivalent to the following declaration.
    ExampleClass instance2 = new ExampleClass();
  • Use object initializers to simplify object creation.

    // Object initializer. 
    var instance3 = new ExampleClass { Name = "Desktop", ID = 37414, 
        Location = "Redmond", Age = 2.3 };
    // Default constructor and assignment statements. 
    var instance4 = new ExampleClass();
    instance4.Name = "Desktop";
    instance4.ID = 37414;
    instance4.Location = "Redmond";
    instance4.Age = 2.3;

Event Handling


    public Form2()
        // You can use a lambda expression to define an event handler. 
        this.Click += (s, e) =>

    // Using a lambda expression shortens the following traditional definition. 
    public Form1()
        this.Click += new EventHandler(Form1_Click);
    void Form1_Click(object sender, EventArgs e)

Static Members

  • Call static members by using the class name: ClassName.StaticMember. This practice makes code more readable by making static access clear. Do not qualify a static member defined in a base class with the name of a derived class. While that code compiles, the code readability is misleading, and the code may break in the future if you add a static member with the same name to the derived class.

LINQ Queries

  • Use meaningful names for query variables. The following example uses seattleCustomers for customers who are located in Seattle.

    var seattleCustomers = from cust in customers
                           where cust.City == "Seattle" 
                           select cust.Name;

  • Use aliases to make sure that property names of anonymous types are correctly capitalized, using Pascal casing.

    var localDistributors =
        from customer in customers
        join distributor in distributors on customer.City equals distributor.City
        select new { Customer = customer, Distributor = distributor };

  • Rename properties when the property names in the result would be ambiguous. For example, if your query returns a customer name and a distributor ID, instead of leaving them as Name and ID in the result, rename them to clarify that Name is the name of a customer, and ID is the ID of a distributor.

    var localDistributors2 =
        from cust in customers
        join dist in distributors on cust.City equals dist.City
        select new { CustomerName = cust.Name, DistributorID = dist.ID };

  • Use implicit typing in the declaration of query variables and range variables.

    var seattleCustomers = from cust in customers
                           where cust.City == "Seattle" 
                           select cust.Name;

  • Align query clauses under the from clause, as shown in the previous examples.

  • Use where clauses before other query clauses to ensure that later query clauses operate on the reduced, filtered set of data.

    var seattleCustomers2 = from cust in customers
                            where cust.City == "Seattle" 
                            orderby cust.Name
                            select cust;

  • Use multiple from clauses instead of a join clause to access inner collections. For example, a collection of Student objects might each contain a collection of test scores. When the following query is executed, it returns each score that is over 90, along with the last name of the student who received the score.

    // Use a compound from to access the inner sequence within each element. 
    var scoreQuery = from student in students
                     from score in student.Scores
                     where score > 90
                     select new { Last = student.LastName, score };