Checking If You Can Use a Class in C#

The is keyword lets you check if a variable is pointing to an object of a particular class (or a class that inherits from some class). For example, the code in this if block only executes if CustomerVariable is pointing at an object of type Customer (or some class that inherits from Customer):

if (CustomerVariable is Customer)
  ...code to execute...

It works with interfaces, too:
if (CustomerVariable is ICustomer)
  ...code to execute ...

You can do your test and get a free cast from a variable by using the as keyword. If the cast fails, no exception is raised, but your destination variable is set to null, telling you that the variable isn't compatible with the object. The following code not only does what the previous code did, but also casts whatever object PremiumCustomerVariable is pointing to into CustomerVariable (if CustomerVariable and the object are compatible, of course):

CustomerVariable = PremiumCustomerVariable as Customer;
if (CustomerVariable != null)
  ...code to execute if PremiumCustomerVariable could be cast as a Customer...

If you want to do the same thing using the variable's class (rather than using some object as the previous examples did) then you want to use IsAssignableFrom:

if (typeof(Customer).IsAssignableFrom(typeof(PremiumCustomer)))
  CustomerVariable = PremiumCustomerVariable;

This also works with interfaces:

if (typeof(ICustomer).IsAssignableFrom(typeof(PremiumCustomer)))
  ICustomerVariable = PremiumVariable;

What other ways do you use to check? Share in the comments section.

Posted by Peter Vogel on 08/04/2015 at 2:20 PM0 comments

Creating a NuGet Web Site

In my regular Practical.NET column, I showed how easy it is to create NuGet packages and discussed how it was a much better way for a developer to share anything you've created, from Entity Framework classes to JavaScript files (my example was a package that implemented an HtmlHelper consisting of a DLL and a JavaScript file). NuGet also allows you to attach searchable documentation to your package to ensure that a developer can find your package, recognize it and know what your code does.

In that article, I showed how to use a folder as a repository for NuGet packages. But if you'd like something a little more professional, you can create a NuGet Web site. It's easy to do: First, in Visual Studio, create an Empty Web Application. Once the project appears in Solution Explorer, right-click on it and select Manage NuGet Packages. In the NuGet Package Manager, do a search for the NuGet.Server package and install it.

After deploying your Website, you just need to do two things:

  1. Save your NuGet packages into the Packages folder in your new site.
  2. Tell Visual Studio about your site.

My earlier article walks through both processes. You can get the information for your site by surfing to it with your browser -- its default page provides both the file path to the folder you should save your package in and the URL you should use when telling Visual Studio about your NuGet site.

I'll put in one caveat: I only tested this on IIS 7.

Posted by Peter Vogel on 12/03/2015 at 10:18 AM0 comments

Convert a List from One Type to Another

You have a List of one object but you really want to have a List of some other object. If it was a single object, you could cast from one to the other with a single line of code:

Dim pCust As PremiumCustomer = New PremiumCustomer
Dim cust As Customer 
cust = pCust

But, because you have a collection of objects, you might assume that you have to write a loop and transfer your objects from one List to the other individually. The good news is that you can do that in one line of code using two LINQ functions: Cast and ToList. Here's the one line solution that creates a list of Customers from a list of a derived class, PremiumCustomers:

Dim pCusts As List(Of CustomerPremium) pCusts = GetPremiumCustomers()
Dim custs As List(Of Customer)
custs = pCusts.Cast(Of Customer)().ToList()

Unlike some "clever" LINQ solutions this one is, I think, actually readable. Under the hood, of course, that loop is probably still being created by LINQ and the compiler…but you don't have to write it. Besides, with this single line of code, the compiler might even be able to invoke some clever optimization to speed up the process.

I didn't come up with this myself: If you're interested there are six more useful LINQ tips where this one came from, all thanks to Igor Ostrovsky.

Posted by Peter Vogel on 06/01/2016 at 11:51 AM0 comments

Comparing Strings Without Worrying About Case

Developers frequently want to ensure two strings are identical without having to worry if some characters are in uppercase in one string and the same characters are in lowercase in the other string. Frequently, you see developers using either ToUpper or ToLower to avoid the problem:

If Name.ToUpper = OtherName.ToUpper Then...

But both ToUpper and ToLower create new strings, which is extra (and unnecessary) work.

If you can live with some extra typing, you can avoid generating those new strings by using the Equals method that every variable has, passing the InvariantCultureIgnoreCase choice from the StringComparison enumeration:

if (Name.Equals(OtherName, StringComparison.InvariantCultureIgnoreCase))

Now you have much less to worry about.

Posted by Peter Vogel on 08/12/2015 at 2:20 PM0 comments

Doing Calculations Right with the Math Class

The .NET Framework gives you the Math class, which has a ton of methods and properties that you can use.

The Abs function will convert negative numbers to positive (and leave positive numbers alone), while the Sign method will tell you if a number is positive, negative or zero.

The Truncate, Ceiling, Floor and Round methods will give you four different ways to get the integer portion of a decimal value, depending on what you want.

The DivRem method will return both the result of a division and its remainder (and IEEERemainder has a special result when you divide a smaller number by a larger number).

The Math object's PI property gives you a value of PI to more than 12 decimals -- more accuracy than you'll probably need.

The Sin, Cos and related methods will perform all of those trigonometry functions that I never really got in high school.

There's more functionality here than I can discuss, but I have to mention the BigMul method (which sounds like the name of a Scottish folk hero to me). When you multiply two large integer numbers you might get a result bigger than an integer … which will cause an overflow exception. BigMul, on the other hand, will multiply two 32-bit integers and return a Long, avoiding overflow.

Maybe it is a folk hero.

Posted by Peter Vogel on 09/15/2016 at 8:19 PM0 comments

Inheriting Interfaces

It's no secret that I love interfaces (I did a whole column about them once). As you add more interfaces to your application you may find that you have several interfaces that look very much alike. These two, for example:

Public Interface ICustomer
    Property Id As Integer
    Property Name As String
    Sub Buy()
End Interface

Public Interface IVendor
    Property Id As Integer
    Property Name As String
    Sub Sell()
End Interface

But, looking at those interfaces, there's obviously the idea of a "business partner" buried in this interface design in the shared Id and Name property. It wouldn't be surprising to find that there are other interfaces in this application that share those Id and Name properties.

You can implement that "business partner" (and simplify maintenance of your application) by defining the business partner interface and then having the ICustomer and IVendor interfaces inherit from it. The result would look like this:

Public Interface IBusinessPartner
    Property Id As Integer
    Property Name As String
End Interface

Public Interface ICustomer
    Inherits IBusinessPartner
    Sub Buy()
End Interface

Public Interface IVendor
    Inherits IBusinessPartner
    Sub Sell()
End Interface

There are lots of benefits to building this inheritance structure: You can now extend both the IVendor and ICustomer interfaces with shared members by adding them to IBusinessPartner. If you ever need to add another "business partner" interface, all the common work is done for you: Your new interface just needs to inherit from IBusinessPartner.

Finally, a variable declared as IBusinessPartner will work with any class that implements ICustomer or IVendor, giving your application more flexibility.

Posted by Peter Vogel on 01/22/2015 at 2:20 PM0 comments

Warn Developers about Using Your Old Code

At least two or three times in my life, I've come back to old systems I'd worked on and realized that I now knew a better way of doing things. However, rather than just revise existing code, that "better way of doing things" required me to write a new method, property or class. When I released my new code out into the world, I wanted to tell other developers to stop using my old code and move to my new code. The best way to do that, I've decided, is to go back to the old code and decorate it with the Obsolete attribute.

You can add the Obsolete attribute either to a class or to members of a class. Regardless, when a developer attempts to use the item you've decorated, they'll get a warning message in their code that says the class (or the member) you've decorated with the attribute is deprecated.

Of course, developers aren't likely to stop using your class or method unless you tell them about your alternative. You can do that by passing a message to the Obsolete attribute -- that message is then tacked onto the end of the attribute's default warning message. This example will generate the message "'SampleClass' is obsolete: Use PHVIS.NewClass" when someone tries to use SampleClass:

<Obsolete("Use PHVIS.NewClass")>
Public Class SampleClass
  Public Sub SampleMethod()

  End Sub
End Class

By default, the Obsolete attribute just generates a warning message so it won't stop the developer's code from compiling. If you want to be more aggressive, you can pass True as the attribute's second parameter to generate a compile-time error and prevent the developer's code from compiling, as this example does:

Public Class SampleClass
  <Obsolete("Use BetterMethod", True)>
  Public Sub SampleMethod()

  End Sub
End Class

I'd wait awhile before doing that, though.

Posted by Peter Vogel on 12/17/2015 at 10:57 AM0 comments

Passing Exception Information

In the bad old days, when an application threw an exception, we frequently extracted the system-generated message and put it on the screen for the user to read. Often it included information that we'd prefer not to share with the outside world (table names and details of the connection string, for instance).

A better practice is to generate an application-specific message that reveals just what you want. And, unlike most system messages that describe what's wrong, your message could tell the user something useful: what to do to solve the problem. A unique message will also help you identify where things have gone wrong in your application. The right answer is to create your own Exception object with a unique message:

Catch Ex As Exception
  Throw New Exception("Something has gone horribly wrong")
End Try

However, when you're debugging, the information you need to prevent the exception from happening again is in the original exception object.

As some readers pointed out to me in comments to an earlier tip, the right answer is to pass the original exception as the second parameter to the Exception object's constructor. Enhancing my earlier code, the result looks like this:

Catch Ex As Exception
  Throw New Exception("Something has gone horribly wrong", Ex)
End Try

The Exception object you pass as the second parameter will show up in the InnerException property of the Exception object you're creating.

Posted by Peter Vogel on 11/13/2014 at 1:51 PM0 comments

NimbleText: An Editor, Only Better

I've admitted it before: Regular expressions defeat me.

NimbleText gives me an editor and an "English-like" way of writing templates that will convert a list of data values into something more useful. Under the hood, it uses regular expressions to identify the data to change but I'm insulated from that. NimbleText isn't a Visual Studio add-in so you have to leave Visual Studio to use it, but even with that limitation NimbleText lets you do wonderful things.

NimbleText is relatively user-friendly: It's well-documented and has menus for selecting and inserting NimbleText keywords into your templates (though many of my templates don't need them). More importantly, NimbleText has a library of snippets to help get you started.

This snippet, for instance, integrates NimbleText keywords and JavaScript to generate C# properties from a list of datatypes and property names:

      <% $0.toLowerCase() %>private $0 <% $1.toCamelCase() %>;

public $0 <% $1.toPascalCase() %> {
  get { return <% $1.toCamelCase() %>; }
  set { <% $1.toCamelCase() %> = value; }

I've also used NimbleText to process text files of data (eliminating duplicate rows, for instance). I can't tell you that the learning curve is zero, but it's pretty darn flat.

Posted by Peter Vogel on 10/02/2014 at 1:51 PM0 comments

Speed Up Apps by Doubling Up on Database Access

The slowest thing you can do in your application is read or write to your hard disk.

The second slowest thing you can do is issue a request to another computer. This means, of course, that whenever you access your database you're doing the two slowest things you can manage. Which means that one of the simplest things you can do to speed up your application is to reduce the number of trips you make to your database, even if you don't make any changes to the amount of data you update or retrieve.

Imagine, for instance, you have this code that first adds a record and then retrieves the number of records present after the insert:

cmd.CommandText = "Insert Into ... ;"

cmd2.CommandText = "Select Count(*) from ... ;"
Dim res As Integer
res = cmd.ExecuteScalar()

As it's written, this is going to involve two trips to the database. There's no reason, however, that the two SQL commands can't be combined into a single request, executed by calling ExecuteScalar:

cmd.CommandText = "Insert Into  ...;" & "Select Count(*) from  ...;"
Dim res As Integer
res = cmd.ExecuteScalar()

Part of the problem is that the ADO.NET method names (ExecuteReader, ExecuteScalar and ExecuteNonQuery) suggest there's only one kind of SQL statement you can use with any method. But, in fact, the three method names really reflect what's returned: ExecuteReader returns a DataReader that will let you work through the rows returned by a Select statement, ExecuteScalar returns the first column of the first row returned by a Select, and ExecuteNonQuery returns the number of rows updated.

You're free to pass any kind of SQL statement (or combination of SQL statements) to any of these methods and it will probably work out for you. If you need, for example, to issue some updates and then retrieve the results, then combine your Update/Insert/Delete statements with a Select statement, execute the commands with a call to ExecuteReader and then use the resulting DataReader to process the rows you get back.

Posted by Peter Vogel on 10/10/2014 at 1:51 PM0 comments

Getting the Second Last Thing You Copied

You copy something in Visual Studio and, before you can paste it you realize that you need to copy something else. Or, worse, you copy something, forget what you're doing, copy something else, go to paste ... and realize that you've lost that first thing you wanted.

Good news! The Visual Studio clipboard actually remembers the last 20 things you cut or copied. To access that history, instead of pressing Ctrl_V to paste your item, just press Shift+Ctl+V. The first time you press that combination you'll paste the last thing you cut or copied; the second time you press it, you'll paste the second last thing you copied right over top of the first item; the third time you press it ... you get the picture.

This feature even works if you press Ctl+V the first time. So, if you paste something you don't want, just switch to Shift+Ctl+V. The first press will get you what you just pasted but your second press will start working you back through your "copy history."

So, go ahead and copy that other thing -- you'll be able to get back to the item currently sitting in the clipboard when you need it.

Posted by Peter Vogel on 12/11/2014 at 1:51 PM0 comments

Create Factory Functions in TypeScript for Creating Multiple Classes

In TypeScript, you can define a function that, when passed a set of parameters, creates and returns a correctly configured object. One of the parameters passed to the function must be the class of the object being created (I'll call that the "class parameter"). Normally, that means your factory function can only create a single kind of class but, by leveraging generics and interfaces, you can create functions that will create and configure a variety of classes.

Your first step is to define an interface that specifies the properties that your factory function will configure. Here's an example of an interface that specifies two properties:

interface ICustomer
  name: string;
  age: number;

With that interface in place you can create a generic factory function that works with any class that implements that interface. First, when defining your factory function, follow the factory function's name with a data type marker and specify that the marker extends the interface. Second, in the factory function's parameter list, use TypeScript's new keyword along with the generic data type marker when defining the function's class parameter (you're actually specifying the type of the class' constructor).

The following code shows the declaration of a generic factory function that leverages my ICustomer interface. I first provide a type marker (c) that, using the extend keyword, ties the function to classes that implement the ICustomer interface. I then use that type marker with the new keyword to specify the return type of the function's class parameter (called cust in my example):

function CreateCustomer<c extends ICustomer>(cust:{new(): c;}, 
                                             name: string, age: number): c

Now, inside my function, I use the class parameter to instantiate the class passed in the class parameter. Once I've done that, I can configure the object by setting the properties specified in the interface:

    var newCust: c;
    newCust = new cust(); = name;
    newCust.age = age;
    return newCust;

To use this factory, I pass the class I want created (which must implement the ICustomer interface) along with the rest of the parameters required by my factory function. This example:

var cust: Customer;
cust = CreateCustomer(Customer, "Peter", 62);

uses my function to create an instance of a class called Customer.

Posted by Peter Vogel on 12/28/2015 at 11:35 AM0 comments

.NET Insight

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.

Upcoming Events