In addition to 'var' (see my other post here), one of the things I really like about C# is that I can both declare, then initialize members of a class using braces, like this...
var reallyLongFooVarName = new ReallyLongFooClassName(){
Name = "I'm an instance of Foo",
ID = 23 };
or even on one line, like this...
var longFooVarName = new ReallyLongFooClassName(){ Name = "I'm an instance of Foo", ID = 23 };
This creates an instance of ReallyLongFooClassName and then sets its members 'Name' and 'ID'.
This compiles to the same thing as if you typed this...
ReallyLongFooClassName reallyLongFooVarName = new ReallyLongFooClassName();
reallyLongFooVarName.Name = "I'm an instance of Foo";
reallyLongFooVarName.ID = 23;
So does Objective-C/C++ have anything equivalent to the member-brace-initialization of C#?
Note: Thanks to my other post, I already know that 'auto' is the 'var' equivalent in Objective-C++ but Objective-C doesn't have any such equal, which is a shame. Again, see my other post here for more info.)
I'm aware of writing initializers. That is a different beat altogether. The technique I demoed above In C# uses the setters of the properties, or sets the member variables directly without having to write a constructor (their sort-of-equivalent to Objective-C's 'init' members.) Having to write init members forces you to have to pre-specify what you want to set. Member brace-initialization lets you specify any combination of properties/member variables and in any order you want. Again, it's just syntactic sugar for writing multiple lines of code at once. It doesn't actually change the class.
There are several alternative if you think of using Objective C/C++.
Objective C:
Create initialization method in class A as;
@interface ClassA:NSObject
-(id)initWithName:(NSString*)name id:(NSUinteger)id;
@end
@implementation ClassA{
NSString *name;
NSUinterger id;
}
-(id)initWithName:(NSString*)name id:(NSUInteger)id{
self = [super init];
if(!self)
return nil;
self -> name = name;
self -> id = id;
return self;
}
Initializing;
[[ClassA alloc] initWithName:@"MyName" id:1000];
Objective C alternative,
Using class or struct;
Using struct;
struct MyClass{
NSString *name;
NSString *identifier;
MyClass(NSString *name, NSUInteger identifier):name(name), identifier(identifier);
};
Initilializing;
MyClass *myclass = new MyClass(@"Sandeep", 1000);
Using class;
class MyClass{
private:
NSString *name;
NSString *identifier;
public:
MyClass(NSString *name = @"", NSUInteger identifier = 0);
};
I think this should some how answer your question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With