Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any way to create standard classes and objects in C# like php

Tags:

c#

object

php

class

In php we can create standard classes and objes like this

< ?php 

$car = new stdClass;
$car->Colour = 'black';
$car->type = 'sports';

print_r($car);
?>

is there any similar way in C#.net ??? I'm very new to C# anyone can help???

like image 591
Ullas Prabhakar Avatar asked Mar 06 '12 15:03

Ullas Prabhakar


People also ask

Can you create objects in C?

Object-Oriented Programming in C Although the fundamental OOP concepts have been traditionally associated with object-oriented languages, such as Smalltalk, C++, or Java, you can implement them in almost any programming language including portable, standard-compliant C (ISO-C90 Standard).

Can you create classes in C?

This document describes the simplest possible coding style for making classes in C. It will describe constructors, instance variables, instance methods, class variables, class methods, inheritance, polymorphism, namespaces with aliasing and put it all together in an example project.

Are there classes and objects in C?

The main purpose of Objective-C programming language is to add object orientation to the C programming language and classes are the central feature of Objective-C that support object-oriented programming and are often called user-defined types.


3 Answers

You could use Anonymous Types in C#, e.g.: taken from the link:

var v = new { Amount = 108, Message = "Hello" };
    Console.WriteLine(v.Amount + v.Message);

Note the Remarks section for their limitations (e.g. can only be cast to object) etc.

like image 161
Jeb Avatar answered Oct 12 '22 04:10

Jeb


C# is statically typed, so regular classes must be declared before they can be used. However, anonymous types allow you to declare classes based on initialization. Once declared neither the type nor the instance can be changed though.

For a more dynamic approach take a look at ExpandoObject which allows dynamically adding properties. This requires C# 4 and the reference must be declared as dynamic.

dynamic car = new ExpandoObject();
car.Color = "Black";
car.Type "Sports";
like image 43
Brian Rasmussen Avatar answered Oct 12 '22 04:10

Brian Rasmussen


You can use anonymous types, but they aren't quite the same: http://msdn.microsoft.com/en-us/library/bb397696.aspx

C# is really all about strong-typing, so weak-type support is, well, pretty weak. Depending on what you're actually doing here, an anonymous type might work, but in general you should create real classes when coding in C#. For your Car example above, I would usually create a class. It's more code, but that's the way C# is. PHP you might create an app with, say, 10 PHP files, but the same C# app will probably end up being 20-30.

like image 40
kitti Avatar answered Oct 12 '22 05:10

kitti