Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why C# Arrays type IsSerializable property is True?

I was just curious why C# arrays return true for their IsSerializable property. Arrays do not have any Serializable attribute, and they also don't implement the ISerializable interface, so why is the IsSerializable property set to true?

When I try the below code, it outputs "True" in the console:

Console.WriteLine (new string[0].GetType().IsSerializable);

The output is:

True

Try it online

My .NET runtime version is 3.5.

like image 482
Empire Avatar asked Sep 05 '17 16:09

Empire


People also ask

Why C is the best language?

It is fast The programs that you write in C compile and execute much faster than those written in other languages. This is because it does not have garbage collection and other such additional processing overheads. Hence, the language is faster as compared to most other programming languages.

Why should you learn C?

Being a middle-level language, C reduces the gap between the low-level and high-level languages. It can be used for writing operating systems as well as doing application level programming. Helps to understand the fundamentals of Computer Theories.

Why do people use C?

The biggest advantage of using C is that it forms the basis for all other programming languages. The mid-level language provides the building blocks of Python, Java, and C++. It's a fundamental programming language that will make it easier for you to learn all other programming languages.

Why semicolon is used in C?

Semicolons are end statements in C. The Semicolon tells that the current statement has been terminated and other statements following are new statements. Usage of Semicolon in C will remove ambiguity and confusion while looking at the code.


1 Answers

Arrays does not have any Serializable attribute and also they aren't implement ISerializable interface

Array class, an implicit base class of C# arrays, has [SerializableAttribute]:

[SerializableAttribute]
[ComVisibleAttribute(true)]
public abstract class Array : ICloneable, IList, ICollection, 
    IEnumerable, IStructuralComparable, IStructuralEquatable

(reference)

It also appears that the compiler adds [SerializableAttribute] to the array type itself

foreach (var a in typeof(string[]).GetCustomAttributes(false)) {
    Console.WriteLine(a); // Prints "System.SerializableAttribute"
}

Passing false to GetCustomAttributes ensures that only attributes for this class, and not for its base classes, are returned.

Demo.

like image 130
Sergey Kalinichenko Avatar answered Oct 18 '22 19:10

Sergey Kalinichenko