Category Archives: C#

Visual Studio smart replace

Let’s say you need to replace an expression in many files in Visual Studio with another expression. The case in question is replacing

nameof(someVariable)
to
"someVariable"

Sure you can try to replace

nameof(
to
"

but this will leave the double quote open and we don’t want this. Searching on the internetz and finding some stackoverflow solution and with the help of a second pair of eyes from a colleague we managed to find a solution like so:

Hit CTRL-SHIFT-H in Visual Studio and check “Use Regular Expressions”. Then select your scope, for example “Entire solution” and use the following expressions:

Find what:
nameof\(([a-zA-z]+)\)

Replace with:
"$1"

This will do the job. Let’s analyze the expressions a bit. The “Find what:” one, first. ‘nameof’ is the literal occurence of ‘nameof’. The first round bracket is preceded by backslash because we need to escape it. This is because the round bracket is used in the regular expressions syntax while in our case we need to literally find it. This was the ‘\(‘ part.

Now there is the ‘([a-zA-z]+)’ part. This has several sub-parts. The round brackets mean that the whole segment should be captured. We’ll later see why and what this is. Next, the square bracket part means that this should match any letter be it uppercase or lowercase (yes, I didn’t handle digits or underscores etc. which may be used in parameter/variable names, that is left as an exercise to the reader :P). The plus sign means the square bracket part may occur multiple times. This means that a parameter/variable name may have more than one such character. Finally we close this part with the round bracket.

The final part in the “Find what:” expression is a literal closing round bracket which, again, is escaped by being prefixed with a backslash.

In the “Replace with:” expression, the captured part in the previous expression (what is enclosed in the regular-expression-syntax round brackets) is expressed as $1, as first numbered. Finally we enclose this in double quotes because that is what we need.

As for why I had to rollback from C# 6 nameof expression to a stringly-typed version, that’s a story for another time, I guess.

Overriding and overloading in Java and .NET – differences, changes and gotchas

Foraying even more in the fundamentals of Java (coming from a .NET background) I’ve come across some interesting things, along with changes in Java SE 5. But first let’s clear up a bit these two notions (overloading and overriding).

Overriding

Is a language feature that allows a subclass/inheriting class to have a method identical (we’ll later see a slight exception to this) to the one in the base class/superclass in every way except the implementation. That is, to have the same return type, the same name, same paramater types, same parameter order, just the code (and the parameter names) can differ.

This is by no means a definitive definition, Wikipedia, .NET CLS’s and JLS may very well differ slightly.

A typical C# overriding example (yes, I also dislike animal examples but they are so eaaaasyyyy to come up with) :

public class Dog 
{
    public virtual void MakeSound()
    {
         Console.WriteLine("Bark.");
    }
}

public class Hound : Dog
{
    public override void MakeSound()
    {
         Console.WriteLine("Wooofff!!!");
    }
}

Java developers unaware of the intricacies of C# will wonder what is that “virtual” thing. In C# all methods are “final” (sealed) by default unlike Java where methods are “virtual” (non-final / non-sealed) by default. This is a profound difference which we’ll discuss later. The “:” stands for “extends”. We’ll discuss the “override” keyword soon, also.

The equivalent piece of code in Java would look like :

public class Dog {
    public void makeSound() {
        System.out.println("Bark.");
    }
}

public class Hound extends Dog {
    public void makeSound() {
        System.out.println("Woofff!!!");
    }
}

Read more »

Numeric literals in Java 7 and in C#

In both Java and C# it’s quite easy to express integer numerical literals. You can use both decimal and hexadecimal base to represent the value. Only for the hexadecimal base you need to prefix the value with 0x. For decimal base values that exceed 2^31-1 you need to provide a suffix (typically L) specifying this fact so the compiler will treat it like a long integer value. C# also provides unsigned long values (U prefix). In both languages the casing of the suffix does not matter.

Java : (notice, there are no unsigned primitives in Java)

int i1 = 23; // integer, decimal
int h1 = 0x17; // integer, hexadecimal
long i2 = 12345678900L; // long integer (64 bit signed integer)

C# :

int i1 = 23;
int h1 = 0x17;
ulong u1 = 12345678900U;
long i2 = 12345678900L;

As you might have read in Beginning Java for .NET developers on slide 14, beginning in Java 7 you can also use two more features, that are not present in C# (at least at the time of this writing) :

Binary base :

int b1 = 0b11001010;

Underscores in literals (no matter which base) :

int b1 = 0b1100_1010;
long myCardNumber = 2315_2432_2111_1110;
int thousandsSeparated = 123_456_000;

The restrictions on the underscore placing is that you may not place it at the beginning of the value (prefix) or at the end (suffix). Also, for non-integer literals, you may not place it adjacent to the decimal separator.

For floating-point literals you must use the dot as decimal separator (if you need to specify a fraction, if not, you’re not required). You must use F for float-single-precision (32 bit) and D for float-double-precision (64 bit). Moreover in C# you have also the M suffix corresponding to the decimal (128 bit) value type.

C# :

float x1 = 0.001F;
double x2 = 12.33D;
decimal x3 = 111.2M;
float x4 = 33F;

Java :

float f1 = 0.001F;
double f2 = 12.31D;
float f3 = 123F;

Enum – comparison of Java and .NET

A useful feature added in Java 1.5 (also known as J2SE 5.0, 2004) is the enum. In .NET enums have been present since the very first version (2002, and as a beta since 2000) but the engineers at Sun managed to learn something from the shortcomings of the enums in .NET and provided more flexibility.

Let’s start with the simplest, the .NET implementation. In .NET all data types, including value types (equivalent of the primitive types) are part of the type hierarchy, being, indirectly inherited from System.Object (equiv. of java.lang.Object). The enums are just a specialization on top of exact numeric types, by default int (System.Int32). A typical declaration :

public enum Month
{
    January,
    February,
    March,
    April,
    May,
    June,
    July,
    August,
    September,
    October,
    November,
    December,
}

Notice that the compiler is forgiving and doesn’t complain that after the last element we forgot to not place a comma. It will also work, of course, if we don’t place a comma after the last element. Behind the scenes the compiler will generate a value-type inheriting from System.Enum that will have 12 constants. By default these constants we’ll be of type Int32 and their value, again, by default, will start from 0 and increase by 1 for each member. January will be 0 and December will be 11. Casts between the backing type (Int32 in this case) and the Months type will be allowed both at design time and at runtime.

You can also force individual values for each member

public enum Month
{
    January = 3,
    February = 33,
    March = 222,
    April = 14,
    May = 20,
    June = 23,
    July,
    August,
    September,
    October,
    November,
    December,
}

In this case January will be equal to 3, February 33, …, June 23, July 24 (not specified but after a value-specified member, the next member will be the last value + 1 if specific value is not present. You can even force things into a bad situation like so :

public enum Months
{
    January = 1,
    February,
    March,
    April,
    May,
    June,
    July = 1,
    August,
    September,
    October,
    November,
    December,
}

Guess what, not only this is completely valid, but there won’t be just two duplicate values (January and July being equal to themselves, and equal to 1) but also February will be 2, just like August and so on. Of course, this is not recommended. The compiler and the runtime will happily apply your stupid scheme but the humans will be confused. This excess of freedom is not to my liking but I can’t do much about it except counter-recommend it. Ideally you should not have to specify values for typical enums. Except for…
Read more »

Simulating C# ref parameter in Java

As I was saying a few posts ago (Beginning Java for .NET Developers), on the 8th slide, there are no ref and no out method parameter modifiers.

These are rarely used in .NET anyway so you can’t really complain of their lack in Java. Furthermore, some of their legitimate uses, such as the static TryParse methods on value types are not applicable in Java. Why? Because in Java the primitives (int, long, byte etc. – the equivalent of the basic value types in .NET) are not part of the type hierarchy and they have reference-type wrappers (Integer etc.) which would solve the issue of returning the result in case of ‘TryParse’ style of parsing. How’s that? It’s like :

public static Integer tryParseInt(String intString) {
    try {
        return Integer.parseInt(intString);
    } catch (NumberFormatException e) {
        return null;
    }
}

No need for a ‘out’ parameter or ‘ref’. But! Let’s try and simulate ‘ref’ using a generic class written this way :

public class Ref<T> {
    private T value;

    public Ref() {
    }

    public Ref(T value) {
        this.value = value;
    }

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return value == null ? null : value.toString();
    }
}

Read more »

Beginning Java for .NET Developers

I’ve always wanted to learn another language and platform and being a long-time .NET developer Java seemed the closest to my knowledge and one which would seem easy to learn based on what I already knew.

I’ve put off this for various reason along the last 3-4 years, most of which laziness was chief.

Recently some colleagues moved from our project to another project that involves Java modules and since .NET is not a first-class citizen in my employer’s eyes I thought maybe it could serve me as a kind of an ‘insurance’ – to learn Java.

I’ve obtained (..) some ebooks (Effective Java and Thinking in Java), downloaded JDK, a few IDEs (IntelliJ IDEA and NetBeans, no Eclipse for me, thanks) and started doing HelloWorld’s and stuff like that. I noticed JavaFX (which is quite similar to WPF on which I currently work)

I’ve came across two nice comparisons of Java and .NET, written in a constructive manner (i.e. not “mine is better, na nanana”) :

Using these two articles I compiled (yes, that’s the original meaning of the word :P) a PowerPoint slideshow.

Then I thought there might be other (.NET developer) colleagues that might be interested in my research and gave an internal presentation based on the slideshow and expanding each item by talk.

I thought I should share it with everyone so here it is (download here) :

I’ve written about Java / C# differences before, and I might continue that series in the near future, with practical examples and counter-examples.

Java / C# differences part 1 of n

Recently I’ve been toying around with Android development (since I own an Android “smart” phone for over 2 years now) and mobile development is all the rage now. Moreover, I’ve been trying to do new things lately since even the pragmatic programmer guide advises us to learn a new language each year (kind of aggressive if you ask me).

Anyway I will try to show what a C# developer (almost 8 years now) discovers by doing Java development on Eclipse for Android.

For today :

leaving a member of a class without an access modifier defaults to internal instead of private :

// C#
void Test() // private method
{
}
// Java
void test() { // internal method
}

Overriding a method does not require any kind of keyword or special ceremony. You can use the @Override annotation but this is optional. You can get burned this way easily.

// C#
public override bool Equals(object other)
{
    return _id == other._id;
}
// Java; WRONG! DO NOT USE
public bool equals(Person other) {
    return this.id == other.id;
}

//Correct
public bool equals(Object other) {
    return this.id == other.id;
}

Overriding requires that you use the same method signature (that is, the same return type, the same parameter types and order). If you accidentally mistake the signature (Person instead of Object) you will overload instead of overriding with unknown effects.

Read more »