Skip navigation

Category Archives: .net

In this series I am going to share with you some programming gems – brief, novel techniques that I’ve picked up over the years that I believe every programmer should know.

Today’s gem: How to Round Up a Float

This isn’t a particularly ground breaking method – most veteran programmers probably know it – but for those of you who don’t, here’s the solution (at least, in most languages):

Add 0.5f to the value and cast it to an integer.  And optionally cast it back to a float, if you need a float.

Here’s the C# extension method that I include in my library project:

        public static float RoundUp(this float f)
            var v = f + 0.5f;
            if (v > int.MaxValue || v < int.MinValue)
                throw new ArgumentException("This value is too large or small to round with this method.  Use decimal formatting instead.", "f");
            return (float)((int)(v));

This works because if the original value’s decimal portion is less than 0.5f, which is the typical median value for rounding, then adding 0.5f to its value will not cause its singles digit to increase.  However, if the decimal portion is greater than 0.5f, the singles digit will increase.  Casting a float to an integer always truncates the decimal portion of the float regardless of its value, and by casting back to a float, you are given a decimal portion of (mostly) zeroes.  I say mostly because as we all know, floating point math is terrible.

The problem with the conversion method is that obviously the range of float is significantly larger than integer, so it doesn’t work for every situation.  Here are the versions I use for other primitives:

        public static decimal RoundUp(this decimal d)
            var dp = d + 0.5m;
            return Math.Truncate(dp);
        public static double RoundUp(this double d)
            var dp = d + 0.5d;
            return Math.Truncate(dp);

This would be the ideal method for floating point numbers as well, but there is no Math.Truncate method overload that takes a float.  I haven’t written one myself simply because I have never found a need to round a float that was larger than 2bn or less than negative 2bn.  If I had a number that large, I would probably just use a double and be done with it.

The reason that I keep the first (flawed) method around is because it’s incredibly easy to code, conserves memory by staying in the 4 byte world, and handles 99.9% of coding situations.  Seriously, how often do you have a float – a float mind you, not a decimal – for a number larger than 2 billion?

Use it, love it.

Speaking of floating point math being terrible, here’s another little gem that I always have in my toolbox:

How to evade the floating point precision dilemma in 1 easy method:

        public static bool Equals(this float f, float otherValue, float margin)
            return Math.Abs(f - otherValue) < margin;
// use it like:
var f = 1.0f;
var g = 1.01f;
var result = f.Equals(g, 0.1f); // value is true

There is probably a stock .NET method for doing this, but I don’t know what it is.  The .NET library is so large that even after working with it for as long as I have, I still find new classes and methods that I never knew about. 

Use this method in place of the == or object.Equals() methods when comparing floating point values.  If you’re going for true equality, set an acceptably low margin value, like 0.00001f.


I’ve spent a few hours trying to unravel SharePoint’s rather scarcely documented schema.xml definition for custom list templates deployeed in features, specifically the <Views> element.

The task: I wanted to render a column in the view that was not based on a field, which as you know, comes from the list values (which come from the database).  In effect, I wanted to create a kind of custom-calculated column.  The “calculation” was an external link to a configurable server URL based on one of the fields in the list.

This was actually easier than I expected.  You need to locate the <View><ViewBody> portion of the schema.xml.  The weirdness comes from the <Fields> element.  As is noted in the Microsoft docs, when the parser comes through and hits the <Fields> element, it treats it as the opening of a loop that essentially says foreach(Field f in list.Fields).  You can render the field in its default manner by using the empty tag <Field/>, so for example in the default view definitions you can copy from the standard SharePoint lists, the body of the <Fields> element is little more than wrapping a <Field> element in some <td> tags to make the columns in table.

If you want to add another column to the end of the table, you are going to want to add a <td> tag after the </Fields> tag (after the loop).  But how do you display a single <Field> value outside of the <Fields> element?

The answer is, I’m pretty sure you can’t.  But what you can do is put a second <Fields> tag in the <ViewBody> tag, and you can use <FieldSwitch> to render only one field.

You do it like this:

                <Property Select=”Name” />
              <Case Value=”YourFieldName”>

As you may know, each field has a collection of properties associated with it.  In the SP Object Model you would get property values by saying list.Fields[“YourFieldName”].GetProperty(“PropertyName”).  In this case, the <expr><property> combo is indicating that you want to compare a field’s “Name” property, and the <Case Value=”YourFieldName”/> means you want to render everything inside the <case> tag when the field’s Name property equals “YourFieldName”.  Pretty straightforward, right?  (By the way, <Column /> is shorthand to render the raw value of the field).

The only problem is that a field’s name according to all of SharePoint’s user interface is actually not its name – it’s its DisplayName property.  For example, the column headers you see at the top of the list are referred to as the field’s name when you modify a list’s columns in the Modify View page, but if you try to use the XML above – namely, select a field based on its Name property by matching <case Value=”YourFieldName”>, nothing will work.  In other words, if the column’s header text is “YourFieldName”, using the above xml snippet just won’t work.

Weird, huh?

In order to figure out what I was doing wrong, I had to set a breakpoint where I could probe my SharePoint list object and figure out what my field’s name was if it wasn’t “MyFieldName”.

Turns out it was “_x0036_F80E0E2_x002d_1798_x002d_”.  Of course.

There’s actually a hint in the SP Object Model API that a field’s “name” for UI purposes is actually not it’s name for API purposes.  Look at this prototype for SPFieldCollection.Add:

public string Add (
    string strDisplayName,
    SPFieldType type,
    bool bRequired

A-ha.  A clue.  It turns out that correct property name to use is DisplayName.  We modify our schema.xml this way:

                <Property Select=”DisplayName” />
              <Case Value=”YourFieldName”>

And like magic, it works like a charm.

Don’t let this one bite you – it took me a few hours of trial and error before I finally figured this one out.

When you are designing a .NET class, always, always use properties.

Don’t create them just as a public accessor.  Wrap 100% of your fields – 100% of which should be private – in properties, even if the property itself is also private.

You should never refer to the field except inside the encapsulating property (including the constructor!  Use the property there, too!).

Before I even begin to point out why you should, I’ll address the immediate knee-jerk reasons why you’ll tell me I’m wrong.

1.  It’s a waste of time.  If you think this is true, you haven’t used Visual Studio long enough.  Right click on your private field and select Refactor, then select Encapsulate Field.  Done.

2.  It bloats the code.  If you think this is true, you haven’t used Visual Studio enough.  Click on the little bordered minus sign in the margin of your code to collapse the property.  You’ve added exactly 1 line to your class definition.  Woe is you!

3.  It’s inefficient.  In practically every place you use them, the C# compiler inlines them.  You were saying?

 4.  It’s non-intuitive from an API consumer’s perspective.  If you don’t have access to the member’s fields, then all you see are properties, which are actually more intuitive because the rest of .NET is written that way.  If you can see the member’s fields and you are following the “everything is private” rule, then you have access to the source code.  If you have access to the source code, then who wrote it, and why are you confused?  Plus, if your team is operating under these guidelines there’s actually less confusion, not more – the confusion would stem from finding a field that doesn’t have a property.

5.  If I make a public property for a field, I don’t want the set to be public, so I don’t include a set on the property and therefore must refer to the field internally.  You need to brush up on your C# – split protection level properties have been around since .NET 2.0.  It’s perfectly legal (although not as common as it should be) to declare a property as:

public string MyString{    get { return _myString; }

    private set { _myString = value; }


6.  It’s pointless.  If you have a private field and a corresponding private property that isn’t any more sophisticated than the Studio-generated encapsulator, then why bother?  I’ll get to that in a minute.

Can you think of any more?  I can’t.

Now, let’s discuss why it’s seriously advantageous to always use properties:

1.  Code safety.  When you are in the habit of always using properties, you always have the opportunity to inject logic surrouding the set and get logic of all the fields, which means part of the natural thought process during design is, “what should I do about nulls?” (among other things).  Once you create the property and you see that you have a method rather than just a field definition, you can surround the field with protective code that will ensure, for example, that if null is passed as the value parameter of your mutator, you don’t replace a list that is by definition always non-null with a null value – instead of assignment, you call the list’s Clear method.  This leads to measurable decreases in exceptions, most of which are hard to trace.

2.  Extensibility.  One of the major advantages of using properties is the ability to allow the data members to also be extensible in derived classes.  If you have a property that returns an IDictionary and your subclass wants to provide a different implementation (Hashtable vs. Red/Black tree, for example), you can override the property.  This is still possible with fields if you defined your field to be IDictionary instead of Dictionary (a rarity amongst most programmers), but it is trivial to come up with examples of times when you would want to be able to redefine the return value of a boolean property, for example.  The base class might just return a bool field, but if they wrapped it in a protected property, the subclass could return the result of a comparison instead of the field (or and it with the field) and the rest of the base class code (which also refers to the property instead of the field) doesn’t change.

3.  It’s so much easier to maintain.  If you use properties exclusively, you only have one “Find All References” search to do to see where your data is being used or manipulated.  If you use a mixmash of the field itself and its encapsulating property, you have to search in two places.  You are never sure if someone is going to use the property or the field so you have to check both, which makes everything you do harder.

4.  It’s so much easier to debug.  I could be accused of not using Studio again here because it is possible to set a breakpoint on a field so that if its value ever changes, your execution breaks and you can see the callstack.  I don’t know about you, but navigating to the property and hitting F9 on get{} and set{} takes me about 1/10th the time of setting up a conditional breakpoint on the value of a field.  If you always use properties everywhere, both internally and externally, and you are wondering “hmm, where does this get changed?”  just pop a breakpoint on the property’s set and reproduce.  It’s just that simple.

I’ll say it again: always use properties.

One of the biggest problems of the concept of null in modern programming languages is the choice API designers have to make between returning null or a conceptually empty object, for example string.Empty or new List<Type>();

On one hand, null is the obvious choice because it prevents wasting resources.  Creating an empty list each time a call returns no results is wasteful.  This can be averted by creating a static empty singleton (like string.Empty), but unless the object is immutable (as string is, or returning a ReadOnlyCollection) you can run into trouble here since the caller can modify the result.  Even this is wasteful when what you’re really trying to say is: “hey, I have no results to return.”  That’s what null means, isn’t it?

On the other hand, for the consumer of an API, even when the API author and the consumer is the same person, it’s hard to guess whether a method will return null or an empty object.  Even the .NET API authors struggle with this fact as evidenced by the string.IsNullOrEmpty static method, which is great for argument and return checking.  Since it’s hard to guess, most good programmers are in the habit of always checking for null first even when they know that the method will never return null because they wrote it.

The reason good programmers check for null religiously is because things change.  You may not be returning null today (in favor of an empty list) but tomorrow you may change your mind.  The problem with an API designer changing his mind is that he can’t predict whether or not the consumers of his API are properly checking for null.  As I said, good programmers will.  But what about the bad ones?

In my opinion, you should generally always return null instead of an empty object except with strings.  The reason for this is that it forces even the average programmer to check for null immediately.  A simple negative unit test will result in a a NullReferenceException.  There is no harm in returning null in version 1.0 and then changing it to return an empty object in version 2.0 but the reverse is deadly, because it has the potential of breaking all your consumers.  Checking for null is benign.  Making the assumption that the result of a method will never be null is an exception waiting to be thrown.

The exception to this rule for strings is because of the string.IsNullOrEmpty method.  Good programmers should rarely check strings of being null or empty independently.  Good APIs do not distinguish between the two in the majority of cases.  In some cases, null is different than empty – for example, in a login form, an empty string means an empty password, but a null password may imply an error occurred somewhere (or may imply integrated security, for which a password is unnecessary).  But generally, this distinction should be obvious from the context.