Archive

Posts Tagged ‘C#’

C# vs Java: casting objects and calling members

February 11th, 2011

Given these two functionally identical code samples in c# and java, what is the output?

C#:

public class A
{
  public String Method()
  {
    return "this is A";
  }
}

public class B : A
{
  public String Method()
  {
    return "this is B";
  }
}

A thisA = new B();

thisA.Method();

Java:

public class A
{
  public String Method()
  {
    return "this is A";
  }
}

public class B extends A
{
  public String Method()
  {
    return "this is B";
  }
}

A thisA = new B();

thisA.Method();

What does thisA.Method() return?

It turns out that there are two different answers to this. In .NET/C# it returns from A (“this is A”). In Java, it returns from B (“this is B”).

So far it appears that this is a type issue; new B() must be getting cast back to A in C#. Looking for some documentation on this specifically. Links anyone?

.NET, Interesting, Technology , ,

Using LINQ to process RegEx matches

December 12th, 2008

Today I used LINQ to help implement a cleaner solution to a problem I was trying to solve. It’s really just some syntactic sugar and a chance to use a buzzword (LINQ).

My simple data class:

?Download download.txt
1
2
3
4
5
public class ReturnRecord
{
    public String FieldKey;
    public String FieldValue;
}

Basically, I needed to return an array with the key/value pairs found in a text document (of type ReturnRecord[]). RegEx was my obvious choice for parsing the text and finding the key value pairs. The keys and values will be decorated with #’s in the document.
Sample text:

?Download download.txt
1
String text = "Blah blah #key#value# blah blah.";

Here is my RegEx setup:

?Download download.txt
1
2
Regex regex = new Regex("#(.+?)#(.+?)#");
MatchCollection keyvalues = regex.Matches(text);

Now I can use a nifty LINQ query to create the array for me without having to write the usual for-loop plumbing. As you can see, LINQ creates the objects and initializes them for me in a single query.

?Download download.txt
1
2
3
4
5
6
7
8
9
List<returnrow> results;
if (keyvalues.Count > 0)
{
results = (from Match m in keyvalues
select new ReturnRow
   { FieldKey = m.Groups[1].Value, 
     FieldValue = m.Groups[2].Value }
     ).ToList();
}</returnrow>

All that’s left is to return

?Download download.txt
1
results.ToArray()

and I’m done. It’s that much less for me to maintain.

MSDN has some examples as well http://msdn.microsoft.com/en-us/library/bb882639.aspx or, check out this post http://schotime.net/index.php/2008/03/10/linq-and-regular-expressions/.

.NET , ,