Is String Type a Class or a Struct? or Something Else

Is String type a class or a struct? Or something else?

If you command+click String in Xcode

struct String {
init()
}

So String is a struct.

You can't subclass from struct as the error message said:

error: Inheritance from non-protocol, non-class type 'String'

However, you can implicitly convert it to NSString (which is subtype of AnyObject) only if you have imported Foundation directly or indirectly.

From REPL

  1> var str = "This is Swift String" 
str: String = "This is Swift String"
2> var anyObj : AnyObject = str
.../expr.oXbYls.swift:2:26: error: type 'String' does not conform to protocol 'AnyObject'
var anyObj : AnyObject = str
^

  1> import Foundation // <---- always imported in any useful application
2> var str = "This is Swift String"
str: String = "This is Swift String"
3> var anyObj : AnyObject = str
anyObj: _NSContiguousString = "This is Swift String" // it is not Swift string anymore
4>

But try to avoid to subclass String or NSString unless you absolute have to. You can read more at NSString Subclassing Notes.

Use extension to add new method to String

extension String {
func print() {
println(self);
}
}

"test".print()

Use delegation pattern if you want to have more control over it

struct MyString {
let str : String = ""

func print() {
println(str)
}
}

Why String is Value type although it is a class not a struct?

System.String is not a value type. It exhibits some behaviors that are similar to value types, but the behavior you have come across is not one of them. Consider the following code.

class Foo 
{
public string SomeProperty { get; private set; }
public Foo(string bar) { SomeProperty = bar }
}

Foo someOtherFoo = new Foo("B");
Foo foo = someOtherFoo;
someOtherFoo = new Foo("C");

If you checked the output of foo.SomeProperty, do you expect it to be the same as someOtherFoo.SomeProperty? If so, you have a flawed understanding of the language.

In your example, you have assigned a string a value. That's it. It has nothing to do with value types, reference types, classes or structs. It's simple assignment, and it's true whether you're talking about strings, longs, or Foos. Your variables temporarily contained the same value (a reference to the string "Ibraheem"), but then you reassigned one of them. Those variables were not inextricably linked for all time, they just held something temporarily in common.

c#: String class vs string struct

They are the same. They are both reference types.

System.String == string
System.Object == object
System.Int32 == int
System.Int64 == long

...etc.

Should I use a structure instead of a class to hold string only data in C#?

I can't see any value in making the customer a struct. The string fields will all be reference types, so you might as well make the whole thing a reference type (ie. class).

I'd be inclined to use one of the built-in collection types rather than create my on type for Customers. Something like:

List<Customer> Customers = new List<Customer>();

Performance of struct containing a string vs class containing a string

The string is for example at address 0x0110 and called "hello". The struct does not store the string itself, it only stores the reference to this string. Thus the struct will only store "0x0110". When you copy the struct, the struct copy will store the same reference "0x0110". Not the string, just the reference. No new string object will be created. But when you change the string in the struct copy, for example from "hello" to "bla", a new string will be created at a new address. For example "bla" will be at address 0x0220. the struct copy will then store "0x0220" instead of "0x0110". The original struct will still store "0x0110". You are now having 2 strings in memory at different adresses.

0x0110 "hello"

0x0220 "bla"

PS: that is a simplification of what really happens.

When should you use a class vs a struct in C++?

The differences between a class and a struct in C++ is:

  • struct members and base classes/structs are public by default.
  • class members and base classes/struts are private by default.

Both classes and structs can have a mixture of public, protected and private members, can use inheritance and can have member functions.

I would recommend you:

  • use struct for plain-old-data structures without any class-like features;
  • use class when you make use of features such as private or protected members, non-default constructors and operators, etc.

What's the difference between struct and class in .NET?

In .NET, there are two categories of types, reference types and value types.

Structs are value types and classes are reference types.

The general difference is that a reference type lives on the heap, and a value type lives inline, that is, wherever it is your variable or field is defined.

A variable containing a value type contains the entire value type value. For a struct, that means that the variable contains the entire struct, with all its fields.

A variable containing a reference type contains a pointer, or a reference to somewhere else in memory where the actual value resides.

This has one benefit, to begin with:

  • value types always contains a value
  • reference types can contain a null-reference, meaning that they don't refer to anything at all at the moment

Internally, reference types are implemented as pointers, and knowing that, and knowing how variable assignment works, there are other behavioral patterns:

  • copying the contents of a value type variable into another variable, copies the entire contents into the new variable, making the two distinct. In other words, after the copy, changes to one won't affect the other
  • copying the contents of a reference type variable into another variable, copies the reference, which means you now have two references to the same somewhere else storage of the actual data. In other words, after the copy, changing the data in one reference will appear to affect the other as well, but only because you're really just looking at the same data both places

When you declare variables or fields, here's how the two types differ:

  • variable: value type lives on the stack, reference type lives on the stack as a pointer to somewhere in heap memory where the actual memory lives (though note Eric Lipperts article series: The Stack Is An Implementation Detail.)
  • class/struct-field: value type lives completely inside the type, reference type lives inside the type as a pointer to somewhere in heap memory where the actual memory lives.

Would there be benefits to a struct String in .Net?

Short Answer

A string has to have a reference type member (e.g., a char[]) in order to be of variable size. Thus any struct String type would really just be a reference type disguised as a value type anyway.


Medium Answer

I discussed this in more depth here. But the basic gist of my idea was: yes, you could have a string "value type," presumably something like this:

public struct String
{
char[] m_characters;

public String(IEnumerable<char> characters)
{
m_characters = characters.ToArray();
}

public char this[int index]
{
get { return m_characters[index]; }
}

// All those other string functions... IndexOf, Substring, etc.
}

...but there's really no point. The above is essentially just a reference type (a wrapper around a char[]) nestled inside a shell that looks deceptively like a value type. Moreover, when you design a type this way you are getting the drawbacks of using a value type (e.g., potential for boxing) with none of the benefit (an instance of the above String type has the same memory allocation requirements as the reference type it wraps, so it buys you nothing from a GC standpoint either).

Struct v/s Class in C# - Please explain the behavior

Classes are reference types, structs are value types.

When a value type is passed to a method as a parameter, a copy of it will be passed through. That means that you add two completely separate copies of the Person struct, one for each pass in the loop.

When a reference type is passed to a method as a parameter, the reference will be passed through. That mean that you add two copies of the reference to the same memory location (to the same Person object) - when making changes to this one object, you see it reflected in both references since they both reference the same object.



Related Topics



Leave a reply



Submit