Some differences in syntax between C# and Java


I learned Java in my freshman year, and recently I have a need to learn C#. It is found that C# and Java are quite similar in some respects, such as:

  • Both C# and Java have no global variables and global functions, and all variables and functions belong to a certain class .
  • Classes are all derived from the Object class, and objects of the class are generated through the keyword new
  • Both C# and JAVA languages ​​​​use the "." operator, no longer use the "->" and "::" operators
  • The if statement in C# and JAVA language does not allow integers as the judgment condition

But for the same knowledge point, the two languages ​​may have slightly different grammar. This article will introduce some differences in grammar between C# and Java, focusing on C#, which can help children's shoes with Java foundation to quickly get started with C#

Compile and run

  • Java is first compiled into a bytecode file (class file), and then interpreted by the JVM into the machine code corresponding to the operating system, which needs to be re-interpreted and executed every time it runs .

  • C# is a language under the .NET platform, and this platform is also compatible with other languages, such as VB. The compilation and operation mechanism of .NET is to compile the source code files (no matter what compatible language) into a unified intermediate language, and then translate the intermediate language into the corresponding machine language at runtime. So there is also a process of compiling -> running.
    Take C# to explain in detail: C# is first compiled into an assembly (exe or dll file) by the C# compiler, and the assembly contains the common intermediate language (CIL). Then CIL is compiled into machine code corresponding to the operating system by the JIT editor in the common language runtime (CLR) in the .NET platform . As long as the program is still resident in memory when it is run again later, the CLR does not need to compile it again.

So there are two processes for executing Java and C# programs: first compile and then run. But the Java runtime is the operation of interpreting the code (sentence-by-sentence translation), and the C# runtime is still the operation of compiling (the whole paragraph is translated uniformly)

program structure

Using the using keyword in C# to refer to the namespace (namespace) is basically the same as using import in Java to import classes in the package, both to avoid naming conflicts.

using System;//C#
import java.util.*   //Java

The file name and class name in C# can be different, but the file name in Java must be the same as the main class name. (Note that the C# script file name in unity must be the same as the main class name)

Method names in C# generally capitalize the first letter of all words (ToString()). (It may take a while for children's shoes from Java to C# to get used to it) Java is generally in camel case, that is, the first letter is capitalized except for the first word (toString()). This is not mandatory, but a programming norm.

variable

Variable names in C# can start with letters, underscores, and @; in Java, they can start with letters, underscores, and $.

constant

C# uses const to declare constants, and Java uses final to declare constants.
It should be noted that in C#, the constants declared inside the class are all static, but static cannot be added. Example:

public class Persons
{
    
            
    public const int SIZE = 10;
    public string[] names; 
                                      
 }    
 class Program    {
    
            
      static void Main(string[] args)int x = Persons.SIZE;   
            Console.ReadKey();        
      }    
 }

It can be seen that although SIZE is not modified with static, we can use variables in the form of "type. variable name", indicating that this const variable is static.
But in Java, static constants must be added static

input Output

Use System.out.println(xxx) to output
Java output, use System.out.printf() to format output

System.out.println("xxx");
int num=1;
System.out.printf("xxx%d",num);

C# output can use Console.WriteLine(xxx) to output a line, and the brackets can be empty, or the output content. The
formatted output of C# is used as follows:

int num=1;
string s="z";
Console.WriteLine("xxx {0} yyy {1}",num,s); //输出xxx 1 yyy z
//或者用:
string s=string.Format("xxx {0} yyy {1}",num,s); 
Console.WriteLine(s);

Here {0} {1} is a placeholder, and the placeholder starts from 0. Since
C#6.0, interpolation strings are also supported , represented by "$":

int num=1;
string s="z";
Console.WriteLine($"xxx {
      
      num} yyy {
      
      s}"); //输出xxx 1 yyy z

Input
Java input with Scanner class

Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
String s=sc.next();

C# input uses Console.ReadLine() Console.Read()
We have seen this writing from the C# initial Hello World program:

Console.WriteLine("Hello World!");
Console.ReadKey();

The function of this ReadKey is to press any key to close the window. Without this line, the console window will flash by, because the program will end after the output is executed. Adding ReadKey is equivalent to waiting for the user's input. This line can also be used in
Console .ReadLine(); Note that this way of writing will terminate the program only after the user enters the carriage return

type of data

Java does not support unsigned types. byte, int, long, etc. are all signed types.
C#'s byte is an 8-bit unsigned integer, and sbyte is an 8-bit signed integer.
There are also uint, ulong, and ushort data types in C#, which are unsigned versions of int, long, and short.

For the Boolean type , Java uses boolean to represent it, and C# uses bool to represent it.

If we want to know the number of bytes occupied by the data type, Java uses a wrapper class (such as Integer.SIZE), and C# uses sizeof(xxx)

In addition, C# adds several special data types:

  1. var
    var is an inferred type, which infers the type of the variable based on the value of the assigned data. Such as var a=1;

  2. dynamic
    A variable of dynamic type in C# can store any type of value, for example: dynamic d = 100;
    any type can be implicitly converted to a dynamic type, such as dynamic d = 100.0;
    in turn, the dynamic type can also be converted into any type, such as int x = d; the compiler will not report an error
    It seems that dynamic and var are somewhat similar. But in fact, var acts on static compilation time, see the following example:

var str="xx";
str=1;

In Visual Studio, as soon as we finish writing this code, the second line will report an error. Because var defines the data type at compile time, once the data type is determined, it cannot be changed at runtime. Therefore, 1 of type int cannot be assigned to str of type string, and they cannot be converted implicitly.
And dynamic acts on the dynamic runtime. No type checking is given at compile time. like:

dynamic str="xx";
str++;

After writing this code, no error will be reported, but when we run this program, VS will give a runtime error, because the ++ operation cannot be performed on string.

  1. Nullable type (? / ??)
    C# provides a special type: nullable type. This type can represent null values ​​in addition to values ​​within the normal range. The method of use is to add a ? . example:
int ?a=null;

The nullable type and the original type are not the same type. If the method requires a parameter of type int, an error will be reported when passing a variable of type int?.
?? represents the Null coalescing operator. If the value of the first operand is null, the operator returns the value of the second operand, otherwise it returns the value of the first operand. For example:

double? num1 = null;         
double num3;         
num3 = num1 ?? 5.34; // num1如果为null返回5.34

string

When defining:

  • The string in Java is the String class , and the string in C# is the string class (note the case).
    Some friends may see the appearance of String in the C# code. In fact, String is a class of the .NET framework. It is not a C# keyword, so if we name a variable as String, it will not report an error, and in C# In the IDE, String will not show a special color, which can also indicate that it is not a keyword.
    Although the C# compiler will eventually compile string into String, we still recommend using string for the sake of specification when writing C# code

  • In addition, C# can use a verbatim string , which treats all escape characters as ordinary characters. The method of use is to add @ before the string:

string str = @"d:\coding\";
//等价于
string str="d:\\coding\\";

After using @, \ will not be regarded as an escape character.

On the method provided:

  • The various string manipulation methods provided by the String class in Java can basically find similar functions in C#.

  • C# compares the content of strings directly with "==" to judge, while Java uses the equals method of the String class. In Java, comparing strings with "==" compares the memory address of the string instead of the content.

  • Variables of basic data types (int, float, etc.) in C# can directly call the ToString() method to convert them into strings. Java uses methods such as String.valueOf(xxx) or Integer.toString(xxx)

//C#
int num=1;
string str=num.ToString();
  • To extract a character at a certain position in a string in Java, use s.charAt(i), and in C# directly use s[i], which is used like an array.

Judge sentences

The syntax of Java and C# is basically the same.
But it should be noted that each case of C#'s switch-case statement must end with a break. Java can not add break

loop statement

C# supports using foreach to iterate arrays or collection objects. An example syntax is as follows:

//C#
int[] array = new int[]{
    
    1,2,3,4,5};  
foreach (int element in array) {
    
        
      ...   
}
//Java 
int[] array = new int[]{
    
    1,2,3,4,5};   
for(int element : array){
    
          
     ...      
 }

access permission

The meanings of public, private, and protected in C# are the same as those in Java. The differences are as follows:

  • There is no concept of package in C#, and naturally there is no package-level private access.
  • C#-specific access rights: internal, meaning that objects in the same assembly can be accessed; protected internal—accessible to derived classes in the same assembly, which is the intersection of internal and protected.
  • C# member variables and member methods default to private, classes default to internal, and interface methods default to public; Java defaults to package-level private except for interfaces that default to public .

method

There are three forms of parameter passing in C#:
(1) Value parameter : the default method, the actual parameter is copied to the formal parameter, and the change of the formal parameter will not change the actual parameter.
(2) Reference parameter : Copy the reference of the memory location of the actual parameter to the formal parameter, and the change of the formal parameter will affect the actual parameter. (Note that attributes cannot be passed as ref parameters, C# attributes will be mentioned later). Reference parameters are declared with ref:

public static void Swap(ref int x, ref int y)
    {
    
    
        int temp;

        temp = x;
        x = y;
        y = temp;
    }
//调用时传参也要加上ref,这种方式会交换x,y的值
int x=1,y=2;
Swap(ref x,ref y);

(3) Output parameters : C#'s return can only return one value from the method, but multiple values ​​can be returned using output parameters. Output parameters are declared with out:

public static void GetValue(out int x){
    
     
      x=5;                  
}

The variable provided to the output parameter does not need to be assigned, but when passing it to the method, out must be added:

int a;
GetValue(out a);    Console.WriteLine(a);

Variable length parameters
If I want to pass in an indeterminate number of parameters of the same type in a method, I can use a variable length parameter list.
The variable-length parameter list in C# is implemented by declaring an array with params in the parameter list of the method (in Java with...):

//C#语法,Java则是用int ... arr
public int AddElements(params int[] arr) {
    
           
     int sum = 0;       
     foreach (int i in arr) {
    
      
          sum += i;       
     }       
     return sum;    
 }
 //然后在调用此方法时就可以用AddElement(1,2,3); 的形式,方法也可以不传参数

Points to note:
1. The parameter type with the params keyword must be a one-dimensional array, and cannot be used on a multi-dimensional array;
2. It is not allowed to be used with ref and out at the same time;
3. The parameter with the params keyword must be the last parameter, And only one params keyword is allowed in a method declaration. For example:

public void Test(int num,string s,params float[] arr){
    
    }

4. Don't use overloaded methods only with params. Consider the following example:

public static void Test(params int[] arr){
    
    }
public static void Test(params string[]arr){
    
    }

At this point we call it like this, without passing parameters:

Test();

At this time, the compiler will report an error. Because the compiler cannot determine which method is called when there are no parameters.

5. Methods without the params keyword have a higher priority than methods with the params keyword. Consider the following example:

public static void Test(string s1,string s2){
    
    
    Console.Write("xx"); 
}
public static void Test(params string[]arr){
    
    
     Console.Write("hh");
}

Then we call this method:

Test("C#","nb");

At this time, xx will be output.
In theory, both methods match, but the first one is actually called, which shows that the first method has a higher priority than the second one.

array

One-dimensional array
C# is also used: data type [] array name = new data type [array length] This form creates a one-dimensional array.
It should be noted that in C#, the array can only be declared in a way similar to int[] array, and the way of int array[] cannot be used. Both are available in Java, but it is recommended to use the form of int[]arr.
For multi-dimensional
arrays in Java, several [ ] are used for several-dimensional arrays. For example, to create a two-dimensional array of int, use: int[ ][ ] arr=new int[number of rows][number of columns]. Then access the element at a certain position in the form of arr[i][j] (note that the array index starts from 0, that is, the element in the first row and first column is arr[0][0])

C# uses [,] to declare a two-dimensional array, [ , , ] to declare a three-dimensional array , and so on. Example:

int[,] array = new int[3, 4]
 {
    
            
     {
    
    1, 2, 3, 4 },        
     {
    
    5, 6, 7, 8 },        
     {
    
    9, 10, 11, 12}    
 };

Then use array[x,y] to refer to the elements of the above array. For example, array[1,2] represents 7 (C# array index also starts from 0, so it represents the element of the second row and third column)

In addition, int[ ][ ] arr also exists in C#, but at this time, instead of simply declaring a two-dimensional array, a staggered array is declared . In the interleaved array, each element of the array stores another array, and the length of each array can be different , so it is also called an array of arrays.
Let's see an example of creating a jagged array:

int[][] arr = new int[3][];

Note:
1) An interleaved array is essentially a one-dimensional array , but the elements inside are also arrays
2) No memory is allocated for the array when it is declared, and each element needs to be created separately in order to use it (instancing each an array element) . Each array element can have a different length.
As far as the above example is concerned, we only stipulate that the array can store three elements, and each element is an array, but we have not yet defined the length of each array element.
We can perform the following initialization methods: (note that the length of each array element can be different)

arr[0] = new int[5];
arr[1] = new int[4];
arr[2] = new int[2];

We can also directly initialize each element within each array element:

int[][] arr = new int[2][]{
    
    
	new int[]{
    
    100,93,94},
	new int[]{
    
    85,60,70,88}
};

3) Use arr[i][j] to get the elements of the interleaved array (same as Java)
4) Use int[ ][ ] arr=new int[i][j] to create an interleaved array . It is not necessary to determine the size at the time of definition. We need to distinguish the concepts of interleaved arrays and two-dimensional arrays. Interleaved arrays are just a special one-dimensional array. We only need to use one parameter to determine the size of the array. As for the size of each array element inside, it is put into the initialization work.

Extra: Int[ ][ ][ ] arr in Java is a three-dimensional array, and C# also has this way of writing, but it is still an interleaved array. It's just an extra layer of baby. The declaration is still a one-dimensional array, and each array element is a jagged array (a one-dimensional array, and each element in the array is another array). This usage may be confusing to understand, but it is generally used less.

enumerated type

Enumerations in C# are similar to C and C++. They are a set of named integer constants, and methods cannot be declared in enumerations like Java . Example:

 //C#用法
 enum Days {
    
     Sun, Mon, tue, Wed, thu, Fri, Sat };

By default, the value of the first enumeration symbol is 0, and the subsequent ones are incremented by 1. However, you can also customize the value of each enumeration symbol by assignment.
Java enumerations can have methods and constructors, such as writing an enumeration that returns results from an API:

public enum ApiErrorCode {
    
    
    SUCCESS(200, "操作成功"),

    private final Integer code;
    private final String message;

    ApiErrorCode(int code, String message) {
    
    
        this.code = code;
        this.message = message;
    }
    public Integer getCode() {
    
    
        return code;
    }
    public String getMessage() {
    
    
        return message;
    }
    
}

kind

  • C# classes support destructors in C++, while Java does not. The destructor is added with a ~ before the class name. It has no return value and does not take any parameters. A destructor is called when an object of a class is destroyed.
public class Person{
    
    
     ~Person(){
    
    
          Console.Write("person");
      }
      static void Main(){
    
    
            Person p=new Person();
       }
}

We only created an object of the Person class. When running this program, we will find that the person is output. This is because the object p will be destroyed at the end of the program, and the destructor of the class will be called at this time.

  • C#'s static initialization block is written differently from Java's static{}, and uses a static constructor:
public class Person{
    
    
     public static int id;
     static Person(){
    
     //这里不用加public
          id=1;
     }
}
  • An ordinary class in Java cannot be defined as static, only an inner class can be a static class.
    In C#, a static class can be defined directly.

    The Java static inner class can access the non-static members of the outer class. When you want to create a static inner class object, you don’t need to instantiate the outer class object, you can directly: Outer.Inner iner = new Outer.Inner(); The
    static class of C# cannot have non-static fields or methods, and the static class cannot be instantiated.

inherit

Suppose now there is a base class Shape, which has a subclass Sphere
1) Basic grammar
C# inheritance writing: class Sphere: Shape;
use: to indicate inheritance, which is the same as C++ grammar.

Java's inheritance method: class Sphere extends Shape. Use the keyword extends

Both C# and Java only support single inheritance.

2) In the constructor, call the constructor of the parent class.
In C#, the writing method is: public Sphere(string name): base(name);

The way to write in Java is to add super (parameter list) to the first line in the constructor. like:

public Sphere(String name) {
    
    
	super(name);
	...
}

To call the method of the parent class in the subclass, C# uses the base. method name; Java uses the super. method name. Both base and super can only call non-static methods of the parent class.

3) Concatenation of constructors
For example, if I want to call another constructor in one constructor,
the writing method in C# is: public Sphere(string name): this(parameter list), and
the writing method in Java is to add this( parameter list).

polymorphism

1) Overloading
The overloading rules of C# are similar to those of Java. Different numbers and types can trigger overloading, but different return value types cannot trigger overloading.
2) To rewrite
member methods that can be overridden by subclasses in C#, you need to add the virtual keyword after the access control permission (similar to C++). By default, all member methods in Java can be overridden by subclasses.

In C#, adding sealed before the class definition can prevent the class from being inherited, and adding sealed in the method means that the method cannot be overridden . Java uses the final keyword to achieve this effect.

In C#, when a subclass overrides the method of the parent class, the override keyword needs to be added, but not in Java.

//C#
public class Person{
    
    
	public virtual void Speak(){
    
    
		Console.WriteLine("I am a person.");
	}
}
public class Student : Person{
    
    
	public override void Speak(){
    
    
		Console.WriteLine("I am a student.");
	}
}

If a method with the same signature is declared in both the base class and the derived class, but the method is not declared as virtual and override respectively, the derived class can add the new keyword to hide the base class method.
like:

class MyBaseClass{
    
    
     public int MyMethod(){
    
    }
}
//派生类(在派生类中把基类同名的方法隐藏掉了)
class MyDerivedClass :MyBaseClass{
    
     
 	 public new void MyMethod() {
    
    }    
}

For example, due to insufficient consideration in the early stage of the project, I did not write the A method in the base class (ClassA), but the A method was written early in the derived class (ClassB) due to requirements, and there are many classes (ClassC, ClassD...) and inherited A derived class (ClassB) is created, and the A method is rewritten. At this time, I want to add the A method to the original base class (ClassA), and I don't want to add override to its derived class. Then there is a way to add the new keyword to the A method in ClassB to hide the A method in the base class

3) Abstract class, abstract method
In C#, a method can be declared as abstract, indicating that the method should be implemented by a subclass. The class containing the abstract method itself must also be abstract, that is, an abstract class that cannot be instantiated. This is similar to Java's abstract usage.

interface

C# does not support multiple inheritance, but it can implement multiple interfaces, just like Java. But C# does not use implements to implement the interface, but directly writes it after the colon like the inherited class, such as:

class Rectangle : Shape, MyInterface

The access rights of methods in interfaces in C# are public by default. The interface supports inheritance, and the interface keyword is also used to define the interface. These are basically the same as Java.

We said before that in C#, the override keyword should be added to the rewritten method, but the method in the implementation interface is an exception. We do not need to add override when rewriting the interface method

abnormal

In C#, you cannot use throws to indicate the type of exception that may be thrown after the method signature, and the rest of the usage (try-catch or throw) is consistent with Java.

generic

In C#, the method of declaring a generic class is the same as in Java. When declaring a class, add <generic parameter list> after the class name, but the syntax for declaring a generic method is different, which is reflected in C# declaring after the method name Generic parameter list, and Java must be declared before the return value . The following is the declaration and use of a generic method in C#:

public static void Swap<T>(ref T a, ref T b)
    {
    
    
        T temp;

        temp = a;
        a = b;
        b = temp;
    }

    static void Main(string[] args)
    {
    
    
        int x = 10;
        int y = 20;
        Swap(ref x, ref y);
        Console.WriteLine(x);
        Console.WriteLine(y);
        Console.ReadLine();
    }

For Java's generic methods, <T> should be moved in front of void. Right now:

public static <T> void swap(T a, T b){
    
    }

(Java does not have ref references to pass parameters, so ref will not be written here)

In addition, when defining generics in C#, you can use the where keyword to limit the range of parameters.
For example:

void Swap<T> (ref T a ,ref T b) where T:class{
    
    }

This limits the incoming parameters to only be of reference type. It will not work if I pass in int type when calling the method, because int is a value type.
Generic qualification:

  • T: struct (type parameter must be a value type. Any value type except Nullable can be specified)
  • T: class (the type parameter must be a reference type, including any class, interface, delegate, or array type)
  • T: new() (The type parameter must have a parameterless public constructor. When used with other constraints the new() constraint must be specified last)
  • T: base class name (the type parameter must be the specified base class or derived from the specified base class)
  • T: interface name (the type parameter must be the specified interface or implement the specified interface. Multiple interface constraints can be specified. Constrained interfaces can also be generic)
  • T: U (The type parameter provided for T must be the parameter provided for U or derived from the parameter provided for U. That is to say, the parameters of T and U must be the same)

Guess you like

Origin blog.csdn.net/qq_46044366/article/details/120012005