Photo of a steaming dark coffee cup

C# (C Sharp) Essentials for Impatient Java Developers: The Basics


One of the problems that I have with a lot of books that purport to teach any given programming language is that they also try to teach programming concepts in the process. Once I've learned them the first time, I've learned them. I don't need to have them reinforced for the umpteenth time; it's just beyond tedious. (That's one of the reasons why I'm not a fan of video tutorials; skipping the content that I already know is not as easy with a video as it is with a book, even if the videos have chapters.) Fortunately, it's not too difficult to do this in the case of learning C#, since I already know Java and C# is pretty much Java on .Net. (C# started out as J#, but there was some disagreement/legal hoohah in which Sun Microsystems issued a cease and desist letter to Microsoft over J#. Microsoft renamed J# to C# and made some changes.)

Another problem that I have is that technology books have a very short shelf life before they're obsolete, particularly at the rate at which languages like Java and C# move. Although I did find a couple of "C# for Java Developer" books, they date from 2002 (which is before I even learned C#, all those years ago.) I didn't think they'd likely be relevant to anyone who wants to develop for versions of Windows or *NIX newer than Windows 2000.

Fortunately, Microsoft has published a C# cheat sheet for Java developers. (It's two A3 pages, one of which I have rotated so that you can print them on opposite sides of the same page and laminate it, if you feel so inclined.) There's the C# Crash course for Java Developers, by Nerd Paradise. IMO, it's rather difficult to follow, as well as being short (which is why I have attempted to merge it with the cheat sheet in writing the below.) Techotopia has also published a C# Essentials guide online, but it's slightly more involved than the Nerd Paradise one and mine. It also focusses exclusively on C#.

Here, then, I offer a middle-ground, a somewhat condensed version from multiple sources (with a recommendation to read the Techotopia guide if you feel this is too confusing or short for your liking/needs). For the most part, the code presented will be in two parts: the Java code, followed by the C# code. In many cases, it will be apparent that it is similar, if not identical.

Note: This post provides only a brief overview of the basics of the C# language, with the assumption that the reader is already familiar with Java. However, you might be able to get a feel for java from it, since I don't present anything too complex or complicated here. For a complete introduction to C# or OOP, please see the recommended books at the end of this post.

Case Sensitivity

Like Java, C# is case-sensitive. (Different capitalisation results in different variables.)

// Java
String fruit = "apple";
String Fruit = "apple";
String FRUIT = "apple";

System.out.println (Fruit);
/* C# allows declarations of multiple variables of the same type in one statement
 * (note lowercase data type)
 */
string fruit = "apple", Fruit = "apple", FRUIT = "apple";

System.out.Console.WriteLine (Fruit); // using the `out` member is optional, but clearer
// Short form, if `Using System;` is placed at top of file
Console.WriteLine ("Something else"); 
// Java requires wrappers around streams
BufferedReader br = new BufferedReader(new InputStreamReader (System.in));
String input = br.readLine (); 
string input = System.in.Console.ReadLine (); // C# makes it simple. `in` is optional.

Constants and Variables

final float PI = 3.145; // Constant in Java
double pie = 22.0 / 7.0;
VeryLongClassName vlcn = new VeryLongClassName ();
const float PI = 3.145; // C# uses `const` instead of `final`
double pie = 22.0 / 7.0;
var vlcn = new VeryLongClassName () ; // C# supports type inference with the `var` keyword

Caveats/Gotchas

  • In Java, bytes are signed. In C#, bytes are unsigned. (To get a signed byte in C#, use the sbyte datatype.)
  • Like in Java, C#'s primitive types are signed. However, C# also offers unsigned types, which generally begin with a u (uint, ulong, etc).
  • Unlike in Java, primitives are also objects in C#. This means that they support calling functions (such as `getType ()`) on them through the member access opperator (`.`). Eg: varName.getType()
  • C# supports casting, just like Java does. In C# there are also built-in methods for type conversion: Convert.ToBoolean (), Convert.ToDouble (), Convert.ToString (), Convert.ToInt32 () (int) and Convert.ToInt64 () (long), similar to Java's .parse* () and .valueOf () methods.
  • Java's boolean is now simply bool in C#.
  • The Java List<> interface is a C# IList because it is an interface.
  • Java's ArrayList<> is just List in C#.
  • Java's HashMap<> is a Dictionary in C#. Java's Map<> is an IDictionary in C#.

String Concatenation and Interpolation

C# provides a number of ways to concatenate strings. It also provides string interpolation.

// Java
String name = "Clive"; // Clive Pringle
String concat = "What were you really doing, " + name + "?";
StringBuilder sb = new StringBuilder ();
sb.append ("What were you really doing, ").append (name).append ("?");
String out = sb.toString (); // Extra call to convert from StringBuilder to String
// C#
string name = "Clive"; // Clive Pringle
string concat = "What were you really doing, " + name + "?";
string interpolated = $"What were you really doing, {name}?";
string build = string.Concat ("What were you really doing, ", name, "?");

For-Each Loop

Java and C# have slightly different syntax for for-each loops:

for ( int key : numArr ) { /* code */ } // Java
foreach (int key in numArr) { /* code */ } // C#

Default Arguments and Named Parameters

C# supports default arguments when defining functions. It also supports named parameters when calling them:

class Person {
  public Person (int age, string firstName, string middleName = '', string surname) {}
}

/* Make a new Person object. Note the order of supplied values */
var LordKelvin = new Person(firstName: "William", surname: "Thompson", age:83);

Classes

Unlike Java, C# supports having multiple classes per file. However, this practice is discouraged.

Caveats/Gotchas

  • Package-scoped classes and methods (i.e. the ones that you didn't declare as either private, public, or protected) have a keyword in C# called internal. These fields/classes are only visible to other code within the same assembly/project (such as a DLL).
  • final has multiple uses in Java. You can declare a class as final, meaning you can't extend it. Alternatively you could set a field or variable as final, meaning you can't modify the value, since it is a constant. For C#, a class from which others can't inherit uses the sealed keyword. A field that you cannot modify uses the readonly or const keywords.

Inheritance and Interfaces

C# has different syntax to Java when it comes to inheritance:

final class subclassName extends superclassName { // Java
  private String memberName;

  public String getMemberName () { return this.memberName; }
  public void setMemberName (String value) { this.memberName = value; }
  
  public subclassName (int x, int y) { super(x, y); }
}
sealed class subclassName : superclassName { // C#; 
// C# Also uses the colon (`:`) for implementing interfaces (names are prefixed with `I`)

  private int numVal; // field; private and lowercase
  public int  NumVal { // Property; public and PascalCase
    get { return numVal; }
    set { numVal = value; } // could have other logic here, as shown below
  }
  public bool IsEven { get { return this.numVal % 2 == 0; } }
  
  subclassName (int x, int y) : base (x, y) {}
}

Namespaces

All classes in C# must be within a namespace. C# uses namespaces (through the namespace keyword) in much the same way as Java uses packages. The difference is that packages must exist in a hierarchy of directories, but namespaces don't have to be organised this way, since the code dictates the hierarchy.

/** file: MyClass.java */
package mine; // exists in the 'mine' directory

public class MyClass {}
/* file: MyClass.cs */
namespace myNamespace { // everything within braces will be within this namespace

  public class MyClass {}

  namespace myNestedNamespace { // myNamespace.myNestedNamespace
    public class MyNestedClass {}
  }
} // end of myNamespace

var anObject = new myNamespace.myNestedNamespace.MyNestedClass ();

Aliases

C# can use aliases for long namespaces. For example:

// To borrow from the previous example ...
// can be shortened by having an alias:
using mine = myNamespace.myNestedNamespace; // uses an alias

namespace anExample {
  public class Program {
    public static void Main (String[] args) {
      var myObj = mine.MyNestedClass();
      string myType = myObj.getType();
      System.out.Console.WriteLine("Hello, world of C# programming!");
      System.out.Console.WriteLine("The type of my object is " + myType + ".");
    }
  }
}

Generics

Once you get onto more advanced topics (such as Collections and Generics), expect to see increasing divergence of C# from Java (especially in more recent versions of the two languages). Here's an example:

List<Integer> list = new LinkedList<>(); // Java List of Integers

static void show (List<Integer>) {
  /* code here */
}
List<string> data = new List<Int32>(); // ArrayList in Java
// Add data here.

// This function can be passed a List<> or IList<>
static void Show (IList<Int32> list) { // Note case of function name
  // Integer and Int32 are interchangeable. Int32 is used by the Common Language Standard
  List<Integer> listOfInts = list.OfType<Integer>();
  /* code here */
}

That should probably be a serviceable introduction, for the most part, although I have forgot to mention some things that are important (such as differences that pertain to Enums) and/or made minor syntax errors I haven't spotted. Now that you've learned some C# without having to wade through several boring chapters in a long-winded book, it's probably a good idea to acquire a copy of Beginning C# 7.0 with Visual Studio 2017 by Benjamin Perkins, et al. [Wrox/Wiley] and diving into chapter 8 (Collections and Generics), possibly moving onto Professional C# 7 and .Net Core by Christian Nagel [Wrox] or Pro C# 7 with .Net and .Net Core by Andrew Troelson and Philip Japikse [Apress]. If I'm not mistaken, Beginning C# 7.0 covers ASP .Net as well.

Note: Although C# 10.0 is the latest version of C#, most developers are still using C# 7.x (.Net Framework 4.7.x) and C# 8.0 (.Net Framework 4.8), so you probably need not learn the latest version for a while.

Errata: All occurrences of System.Out.Console should be System.Console.Out and all occurrences of System.In.Console should be System.Console.Out. Also, if you place using static System.Console; at the top of a file, you don't have to type System.Console every time you want to use it. (Doing so will save you plenty of keystrokes, which can potentially speed up your development.)

Happy coding!


Post image: Photo by Alex Azabache on Pexels

How do you rate this article?

7


Great White Snark
Great White Snark

I'm currently seeking fixed employment as a S/W & Web developer (C# & ASP .NET MVC, PHP 8+, Python 3), hoping to stash the farmed fiat and go full Crypto, quit the 07:30-18:00 grind. Unsigned music producer; snarky; white; balding; smashes Patriarchy.


Return to the Source
Return to the Source

Use the Force; read the source! This blog is mostly a collection of study notes on ASM, ASP .NET, Blender, BASIC, C/C++, C#, ChucK, Computer Architecture, Computer Literacy, CSS, Digital Logic, Electronics, F#, GIMP, GTK+, Haskel, Java, Julia, JavaScript (ES6+) & JSON, LISP, Nim, OOP, Photoshop, PLAD, Python, Qt, Ruby, Scheme, SQL (MySQL & SQLite), Super Collider, UML, Verilog, VHDL, WASM, XML. If I can learn it and make notes on it, I'll write about it. || Blog images copyright Markus Spiske and Pixabay

Publish0x

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.