C# and its differences with Java part 1
What is C#?
C# is an object-oriented programming language developed by Microsoft during the development of the .NET framework and was led by Anders Hejlberg. It is based on the languages C and C++, it also shares a strong resemblance with Java which makes it easier to learn for programmers that has knowledge of Java.
In Java we have the concept of packages which contains classes and interfaces, C# also shares a similar concept which is called namespaces.
The following code is an example of what Java packages look like
public class MyClass
In Java the source file can only contain one package and is declared at the top.
The next example is what namespaces can look like for C#
In C# a source file is not limited to only one namespace, the source file can include multiple namespaces and even a nested namespace. One more thing to note is that in C# the namespace wraps all of its types.
Class Access (import/using)
In java the keyword used in order to access classes in other packages is import, while the keyword for C# is using.
In the example above it imports the util package which will grant the developer access to the classes inside it.
using MyList = System.Collections.ArrayList;
public void MyMethod()
MyList lst = new MyList();
In C# using can be used to access classes from a different namespace which is shown in the first line of the example above. In the second line it demonstrates the syntax for declaring type aliases which is another use of the using keyword.
Java and C# has a few similarities in access modifiers as well (ex. private, public), but C# has a few more which are:
- internal — access is limited to the classes in the same assembly.
- protected internal — access is limited to the classes in the same assembly or types derived from the containing class.
When a member does not have an access modifier it would use its default access modifier which depends on what type of member it is.
Member = Default Access Modifier
- class = private
- enum = public
- struct = private
- interface = public
User Inputs & System printouts
A function to read the user input from the console and display messages on the console also exists for both Java and C# but looks different from each other.
Reading user input from Java:
Scanner s = new Scanner(System.in);
text = s.nextLine();//reads user input
System.out.println(s);//prints the s value to the console
Reading user input from C#:
string s = Console.ReadLine();//reads user input
Console.WriteLine(s);//prints the s value to the console
In C# the user can define his/her own value type using the keyword struct. This can be used to encapsulate groups of related variables. For example a person has the characteristics of age and gender, in C# we can use a struct to contain the age and gender values of the person.
public struct Person
public int age;
public string gender;
To be continued on the next post.