Search Results

Search found 47245 results on 1890 pages for 'class members'.

Page 8/1890 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Request for advice about class design, inheritance/aggregation

    - by Lasse V. Karlsen
    I have started writing my own WebDAV server class in .NET, and the first class I'm starting with is a WebDAVListener class, modelled after how the HttpListener class works. Since I don't want to reimplement the core http protocol handling, I will use HttpListener for all its worth, and thus I have a question. What would the suggested way be to handle this: Implement all the methods and properties found inside HttpListener, just changing the class types where it matters (ie. the GetContext + EndGetContext methods would return a different class for WebDAV contexts), and storing and using a HttpListener object internally Construct WebDAVListener by passing it a HttpListener class to use? Create a wrapper for HttpListener with an interface, and constrct WebDAVListener by passing it an object implementing this interface? If going the route of passing a HttpListener (disguised or otherwise) to the WebDAVListener, would you expose the underlying listener object through a property, or would you expect the program that used the class to keep a reference to the underlying HttpListener? Also, in this case, would you expose some of the methods of HttpListener through the WebDAVListener, like Start and Stop, or would you again expect the program that used it to keep the HttpListener reference around for all those things? My initial reaction tells me that I want a combination. For one thing, I would like my WebDAVListener class to look like a complete implementation, hiding the fact that there is a HttpListener object beneath it. On the other hand, I would like to build unit-tests without actually spinning up a networked server, so some kind of mocking ability would be nice to have as well, which suggests I would like the interface-wrapper way. One way I could solve this would be this: public WebDAVListener() : WebDAVListener(new HttpListenerWrapper()) { } public WebDAVListener(IHttpListenerWrapper listener) { } And then I would implement all the methods of HttpListener (at least all those that makes sense) in my own class, by mostly just chaining the call to the underlying HttpListener object. What do you think? Final question: If I go the way of the interface, assuming the interface maps 1-to-1 onto the HttpListener class, and written just to add support for mocking, is such an interface called a wrapper or an adapter?

    Read the article

  • Get information from a higher class?

    - by Clint Davis
    I don't know really how to word the question so please bear with me... I have 3 classes: Server, Database, and Table. Each class has a "Name" property. How I want it to work is that each server can have multiple databases and each database can have multiple tables. So in the Server class I have this property. Private _databases As List(Of Database) Public Property Databases() As List(Of Database) Get Return _databases End Get Set(ByVal value As List(Of Database)) _databases = value End Set End Property And I have something similar in the Database class for the tables. This works fine now because I can do something like this to get all the databases in the server. For Each db In s.Databases 's being the server object Debug.Print(db.Name) Next I would like to expand these classes. I want the server class to handle all the connection information and I would like the other classes to use the server class's connection information in them. For example, I setup a server class and set the connection string to the server. Then I want the database class to use serverclass.connectionstring property to connect to the server and get a list of all the databases. But I want to keep that code in the database class. How can I do this? I've attached some code of what I want to do. Public Class Server Private _name As String Public Property Name() As String Get Return _name End Get Set(ByVal value As String) _name = value End Set End Property Private _databases As List(Of Database) Public Property Databases() As List(Of Database) Get Return _databases End Get Set(ByVal value As List(Of Database)) _databases = value End Set End Property End Class '-----New class Public Class Database Private _name As String Public Property Name() As String Get Return _name End Get Set(ByVal value As String) _name = value End Set End Property Private _tables As List(Of Table) Public Property Tables() As List(Of Table) Get Return _tables End Get Set(ByVal value As List(Of Table)) _tables = value End Set End Property 'This is where I need help! Private Sub LoadTables () dim connectionstring as string = server.connectionstring 'Possible? 'Do database stuff End Class Thanks for reading!

    Read the article

  • Is it legal to extend the Class class?

    - by spiralganglion
    I've been writing a system that generates some templates, and then generates some objects based on those templates. I had the idea that the templates could be extensions of the Class class, but that resulted in some magnificent errors: VerifyError: Error #1107: The ABC data is corrupt, attempt to read out of bounds. What I'm wondering is if subclassing Class is even possible, if there is perhaps some case where doing this would be appropriate, and not just a gross misuse of OOP. I believe it should be possible, as ActionScript allows you to create variables of the Class type. This use is described in the LiveDocs entry for Class, yet I've seen no mentions of subclassing Class. Here's a pseudocode example: class Foo extends Class var a:Foo = new Foo(); trace(a is Class) // true, right? var b = new a(); I have no idea what the type of b would be. In summary: can you subclass the Class class? If so, how can you do it without errors, and what type are the instances of the instances of the Class subclass?

    Read the article

  • Function returning a class containing a function returning a class

    - by Scott
    I'm working on an object-oriented Excel add-in to retrieve information from our ERP system's database. Here is an example of a function call: itemDescription = Macola.Item("12345").Description Macola is an instance of a class which takes care of database access. Item() is a function of the Macola class which returns an instance of an ItemMaster class. Description() is a function of the ItemMaster class. This is all working correctly. Items can be be stored in more than one location, so my next step is to do this: quantityOnHand = Macola.Item("12345").Location("A1").QuantityOnHand Location() is a function of the ItemMaster class which returns an instance of the ItemLocation class (well, in theory anyway). QuantityOnHand() is a function of the ItemLocation class. But for some reason, the ItemLocation class is not even being intialized. Public Function Location(inventoryLocation As String) As ItemLocation Set Location = New ItemLocation Location.Item = item_no Location.Code = inventoryLocation End Function In the above sample, the variable item_no is a member variable of the ItemMaster class. Oddly enough, I can successfully instantiate the ItemLocation class outside of the ItemMaster class in a non-class module. Dim test As New ItemLocation test.Item = "12345" test.Code = "A1" quantityOnHand = test.QuantityOnHand Is there some way to make this work the way I want? I'm trying to keep the API as simple as possible. So that it only takes one line of code to retrieve a value.

    Read the article

  • accessing c++ class members with luaplus

    - by cppanda
    i've implemented LuaPlus in my engine eventmanager successfully and really like the flexibility i gained. but i'm still not exactly where i want to by, because i can't link my c++ classes to a lua class. for example i have a Actor class in c++, and i want to be able to create the same class in lua and gain access to members with luaplus, but i can't figure how i can achieve that. Is this actually luaplus built in functionality, or do i have to write my own interface that exchanges data tables between c++ and lua? my current approach would be to fire an event in luascript that creates an new actor class in c++ code, and transfer its id and the data i need to back to lua. when i modify the data i send the modifications back to c++ code again, but i actually thought there's something in luaplus that exposes this functionality already.

    Read the article

  • Gathering IP address and workstation information; does it belong in a state class?

    - by p.campbell
    I'm writing an enterprisey utility that collects exception information and writes to the Windows Event Log, sends an email, etc. This utility class will be used by all applications in the corporation: web, BizTalk, Windows Services, etc. Currently this class: holds state given to it via public properties calls out to .NET Framework methods to gather information about runtime details. Included are call to various properties and methods from System.Environment, Reflection details, etc. This implementation has the benefit of allowing all those callers not to have to make these same calls themselves. This means less code for the caller to forget, screw up, etc. Should this state class (please what's the phrase I'm looking for [like DTO]?) know how to resolve/determine runtime details (like the IP address and machine name that it's running on)? It seems to me on second thought that it's meant to be a class that should hold state, and not know how to call out to the .NET Framework to find information. var myEx = new AppProblem{MachineName="Riker"}; //Will get "Riker 10.0.0.1" from property MachineLongDesc Console.WriteLine("full machine details: " + myEx.MachineLongDesc); public class AppProblem { public string MachineName{get;set;} public string MachineLongDesc{ get{ if(string.IsNullOrEmpty(this.MachineName) { this.MachineName = Environment.MachineName; } return this.MachineName + " " + GetCurrentIP(); } } private string GetCurrentIP() { return System.Net.Dns.GetHostEntry(this.MachineName) .AddressList.First().ToString(); } } This code was written by hand from memory, and presented for simplicity, trying to illustrate the concept.

    Read the article

  • class __init__ (not instance __init__)

    - by wallacoloo
    Here's a very simple example of what I'm trying to get around: class Test(object): some_dict = {Test: True} The problem is that I cannot refer to Test while it's still being defined Normally, I'd just do this: class Test(object): def __init__(self): self.__class__.some_dict = {Test: True} But I never create an instance of this class. It's really just a container to hold a group of related functions and data (I have several of these classes, and I pass around references to them, so it is necessary for Test to be it's own class) So my question is, how could I refer to Test while it's being defined, or is there something similar to __init__ that get's called as soon as the class is defined? If possible, I want self.some_dict = {Test: True} to remain inside the class definition. This is the only way I know how to do this so far: class Test(object): @classmethod def class_init(cls): cls.some_dict = {Test: True} Test.class_init()

    Read the article

  • Derive abstract class from non-abstract class

    - by Jehof
    Is it OK to derive an abstract class from a non-abstract class or is there something wrong with this approach? Here´s a little example: public class Task { // Some Members } public abstract class PeriodicalTask : Task { // Represents a base class for task that has to be done periodicaly. // Some additional Members } public class DailyTask : PeriodicalTask { // Represents a Task that has to be done daily. // Some additional Members } public class WeeklyTask : PeriodicalTask { // Represents a Task that has to be done weekly. // Some additional Members } In the example above i do not want to make the class Task abstract, because i want to instantiate it directly. PeriodicalTask should inherit the functionality from Task and add some additional members but i do not want to instantiate it directly. Only derived class of PeriodicalTask should be instantiated.

    Read the article

  • Is it possible to shorten my main function in this code?

    - by AjiPorter
    Is it possible for me to shorten my main() by creating a class? If so, what part of my code would most likely be inside the class? Thanks again to those who'll answer. :) #include <iostream> #include <fstream> #include <string> #include <ctime> #include <cstdlib> #define SIZE 20 using namespace std; struct textFile { string word; struct textFile *next; }; textFile *head, *body, *tail, *temp; int main() { ifstream wordFile("WORDS.txt", ios::in); // file object constructor /* stores words in the file into an array */ string words[SIZE]; char pointer; int i; for(i = 0; i < SIZE; i++) { while(wordFile >> pointer) { if(!isalpha(pointer)) { pointer++; break; } words[i] = words[i] + pointer; } } /* stores the words in the array to a randomized linked list */ srand(time(NULL)); int index[SIZE] = {0}; // temporary array of index that will contain randomized indexes of array words int j = 0, ctr; // assigns indexes to array index while(j < SIZE) { i = rand() % SIZE; ctr = 0; for(int k = 0; k < SIZE; k++) { if(!i) break; else if(i == index[k]) { // checks if the random number has previously been stored as index ctr = 1; break; } } if(!ctr) { index[j] = i; // assigns the random number to the current index of array index j++; } } /* makes sure that there are no double zeros on the array */ ctr = 0; for(i = 0; i < SIZE; i++) { if(!index[i]) ctr++; } if(ctr > 1) { int temp[ctr-1]; for(j = 0; j < ctr-1; j++) { for(i = 0; i < SIZE; i++) { if(!index[i]) { int ctr2 = 0; for(int k = 0; k < ctr-1; k++) { if(i == temp[k]) ctr2 = 1; } if(!ctr2) temp[j] = i; } } } j = ctr - 1; while(j > 0) { i = rand() % SIZE; ctr = 0; for(int k = 0; k < SIZE; k++) { if(!i || i == index[k]) { ctr = 1; break; } } if(!ctr) { index[temp[j-1]] = i; j--; } } } head = tail = body = temp = NULL; for(j = 0; j < SIZE; j++) { body = (textFile*) malloc (sizeof(textFile)); body->word = words[index[j]]; if(head == NULL) { head = tail = body; } else { tail->next = body; tail = body; cout << tail->word << endl; } } temp = head; while(temp != NULL) { cout << temp->word << endl; temp = temp->next; } return 0; }

    Read the article

  • Java - abstract class, equals(), and two subclasses

    - by msr
    Hello, I have an abstract class named Xpto and two subclasses that extend it named Person and Car. I have also a class named Test with main() and a method foo() that verifies if two persons or cars (or any object of a class that extends Xpto) are equals. Thus, I redefined equals() in both Person and Car classes. Two persons are equal when they have the same name and two cars are equal when they have the same registration. However, when I call foo() in the Test class I always get "false". I understand why: the equals() is not redefined in Xpto abstract class. So... how can I compare two persons or cars (or any object of a class that extends Xpto) in that foo() method? In summary, this is the code I have: public abstract class Xpto { } public class Person extends Xpto{ protected String name; public Person(String name){ this.name = name; } public boolean equals(Person p){ System.out.println("Person equals()?"); return this.name.compareTo(p.name) == 0 ? true : false; } } public class Car extends Xpto{ protected String registration; public Car(String registration){ this.registration = registration; } public boolean equals(Car car){ System.out.println("Car equals()?"); return this.registration.compareTo(car.registration) == 0 ? true : false; } } public class Teste { public static void foo(Xpto xpto1, Xpto xpto2){ if(xpto1.equals(xpto2)) System.out.println("xpto1.equals(xpto2) -> true"); else System.out.println("xpto1.equals(xpto2) -> false"); } public static void main(String argv[]){ Car c1 = new Car("ABC"); Car c2 = new Car("DEF"); Person p1 = new Person("Manel"); Person p2 = new Person("Manel"); foo(p1,p2); } }

    Read the article

  • VIrtual class problem

    - by ugur
    What i think about virtual class is, if a derived class has a public base, let's say, class base, then a pointer to derived can be assigned to a variable of type pointer to base without use of any explicit type conversion. But what if, we are inside of base class then how can we call derived class's functions. I will give an example: class Graph{ public: Graph(string); virtual bool addEdge(string,string); } class Direct:public Graph{ public: Direct(string); bool addEdge(string,string); } Direct::Direct(string filename):Graph(filename){}; When i call constructor of Direct class then it calls Graph. Now lets think Graph function calls addedge. Graph(string str){ addedge(str,str); } When it calls addedge, even if the function is virtual, it calls Graph::edge. What i want is, to call Direct::addedge. How can it be done?

    Read the article

  • Virtual class problem

    - by ugur
    What i think about virtual class is, if a derived class has a public base, let's say, class base, then a pointer to derived can be assigned to a variable of type pointer to base without use of any explicit type conversion. But what if, we are inside of base class then how can we call derived class's functions. I will give an example: class Graph{ public: Graph(string); virtual bool addEdge(string,string); } class Direct:public Graph{ public: Direct(string); bool addEdge(string,string); } Direct::Direct(string filename):Graph(filename){}; When i call constructor of Direct class then it calls Graph. Now lets think Graph function calls addedge. Graph(string str){ addedge(str,str); } When it calls addedge, even if the function is virtual, it calls Graph::edge. What i want is, to call Direct::addedge. How can it be done?

    Read the article

  • Python overriding class (not instance) special methods

    - by André
    How do I override a class special method? I want to be able to call the __str__() method of the class without creating an instance. Example: class Foo: def __str__(self): return 'Bar' class StaticFoo: @staticmethod def __str__(): return 'StaticBar' class ClassFoo: @classmethod def __str__(cls): return 'ClassBar' if __name__ == '__main__': print(Foo) print(Foo()) print(StaticFoo) print(StaticFoo()) print(ClassFoo) print(ClassFoo()) produces: <class '__main__.Foo'> Bar <class '__main__.StaticFoo'> StaticBar <class '__main__.ClassFoo'> ClassBar should be: Bar Bar StaticBar StaticBar ClassBar ClassBar Even if I use the @staticmethod or @classmethod the __str__ is still using the built in python definition for __str__. It's only working when it's Foo().__str__() instead of Foo.__str__().

    Read the article

  • Flash AS3 - Dispatching Events from Parent Class to Child Class

    - by John Russell
    I think this is a pretty simply problem but I do not seem to be able to pull it off. Basically I have a parent class A, and a child class B. Class A instantiates class B with addChild. There is a shared object which is being updated from a java server (red5) that has an event listener attached to it in class A. I have a function in class A which will pass certain, specific updates from this shared object to class B. The problem occurs is that when class B is instantiated, the event listener from class A doesn't work anymore. I have not removed the event listener from A. Any thoughts?

    Read the article

  • Override bits of a CSS class while inline?

    - by larryq
    I have an html img that is being styled by a CSS class. I would like to override the width and height values used in that class under some circumstances. I'm building this img tag using something called a TagBuilder class, provided by Microsoft for the .Net system, which allows developers to assign attributes to an html element. In this case a CSS class has been assigned to the img tag, and I can assign width and height attributes individually, but they're not taking precedence over the values set in the CSS class. My tag looks like this currently: <img alt="my link" class="static" height="240" id="StaticImage" src="http://imageserver.com/myImage.jpg" width="240"> The static CSS class has width and height values of 300 each, and as you can see I'm trying to override them with 240. It's not working in this instance but can I do it without a second CSS class?

    Read the article

  • python class attribute

    - by chnet
    Hi, i have a question about class attribute in python. class base : def __init__ (self): pass derived_val = 1 t1 = base() t2 = base () t2.derived_val +=1 t2.__class__.derived_val +=2 print t2.derived_val # its value is 2 print t2.__class__.derived_val # its value is 3 The results are different. I also use id() function to find t2.derived_val and t2.class.derived_val have different memory address. My problem is derived_val is class attribute. Why it is different in above example? Is it because the instance of class copy its own derived_val beside the class attribute?

    Read the article

  • Python Class inherit from all submodules

    - by Dhruv Govil
    I'm currently writing a wrapper in python for a lot of custom company tools. I'm basically going to break each tool into its own py file with a class containing the call to the tool as a method. These will all be contained in a package. Then there'll be a master class that will import all from the package, then inherit from each and every class, so as to appear as one cohesive class. masterClass.py pyPackage - __ init__.py - module1.py --class Module1 ---method tool1 - module2.py --class Module2 ---method tool2 etc Right now, I'm autogenerating the master class file to inherit from the packages modules, but I was wondering if there was a more elegant way to do it? ie from package import * class MasterClass(package.all): pass

    Read the article

  • Getting count() of class static array

    - by xylar
    Is it possible to get the count of a class defined static array? For example: class Model_Example { const VALUE_1 = 1; const VALUE_2 = 2; const VALUE_3 = 3; public static $value_array = array( self::VALUE_1 => 'boing', self::VALUE_2 => 'boingboing', self::VALUE_3 => 'boingboingboing', ); public function countit() { // count number $total = count(self::$value_array ); echo ': '; die($total); } } At the moment calling the countit() method returns :

    Read the article

  • cast operator to base class within a thin wrapper derived class

    - by miked
    I have a derived class that's a very thin wrapper around a base class. Basically, I have a class that has two ways that it can be compared depending on how you interpret it so I created a new class that derives from the base class and only has new constructors (that just delegate to the base class) and a new operator==. What I'd like to do is overload the operator Base&() in the Derived class so in cases where I need to interpret it as the Base. For example: class Base { Base(stuff); Base(const Base& that); bool operator==(Base& rhs); //typical equality test }; class Derived : public Base { Derived(stuff) : Base(stuff) {}; Derived(const Base& that) : Base(that) {}; Derived(const Derived& that) : Base(that) {}; bool operator==(Derived& rhs); //special case equality test operator Base&() { return (Base&)*this; //Is this OK? It seems wrong to me. } }; If you want a simple example of what I'm trying to do, pretend I had a String class and String==String is the typical character by character comparison. But I created a new class CaseInsensitiveString that did a case insensitive compare on CaseInsensitiveString==CaseInsensitiveString but in all other cases just behaved like a String. it doesn't even have any new data members, just an overloaded operator==. (Please, don't tell me to use std::string, this is just an example!) Am I going about this right? Something seems fishy, but I can't put my finger on it.

    Read the article

  • Getting the name of a child class in the parent class (static context)

    - by Benoit Myard
    Hi everybody, I'm building an ORM library with reuse and simplicity in mind; everything goes fine except that I got stuck by a stupid inheritance limitation. Please consider the code below: class BaseModel { /* * Return an instance of a Model from the database. */ static public function get (/* varargs */) { // 1. Notice we want an instance of User $class = get_class(parent); // value: bool(false) $class = get_class(self); // value: bool(false) $class = get_class(); // value: string(9) "BaseModel" $class = __CLASS__; // value: string(9) "BaseModel" // 2. Query the database with id $row = get_row_from_db_as_array(func_get_args()); // 3. Return the filled instance $obj = new $class(); $obj->data = $row; return $obj; } } class User extends BaseModel { protected $table = 'users'; protected $fields = array('id', 'name'); protected $primary_keys = array('id'); } class Section extends BaseModel { // [...] } $my_user = User::get(3); $my_user->name = 'Jean'; $other_user = User::get(24); $other_user->name = 'Paul'; $my_user->save(); $other_user->save(); $my_section = Section::get('apropos'); $my_section->delete(); Obviously, this is not the behavior I was expecting (although the actual behavior also makes sense).. So my question is if you guys know of a mean to get, in the parent class, the name of child class.

    Read the article

  • Class initialization and synchronized class method

    - by nybon
    Hi there, In my application, there is a class like below: public class Client { public synchronized static print() { System.out.println("hello"); } static { doSomething(); // which will take some time to complete } } This class will be used in a multi thread environment, many threads may call the Client.print() method simultaneously. I wonder if there is any chance that thread-1 triggers the class initialization, and before the class initialization complete, thread-2 enters into print method and print out the "hello" string? I see this behavior in a production system (64 bit JVM + Windows 2008R2), however, I cannot reproduce this behavior with a simple program in any environments. In Java language spec, section 12.4.1 (http://java.sun.com/docs/books/jls/second_edition/html/execution.doc.html), it says: A class or interface type T will be initialized immediately before the first occurrence of any one of the following: T is a class and an instance of T is created. T is a class and a static method declared by T is invoked. A static field declared by T is assigned. A static field declared by T is used and the reference to the field is not a compile-time constant (§15.28). References to compile-time constants must be resolved at compile time to a copy of the compile-time constant value, so uses of such a field never cause initialization. According to this paragraph, the class initialization will take place before the invocation of the static method, however, it is not clear if the class initialization need to be completed before the invocation of the static method. JVM should mandate the completion of class initialization before entering its static method according to my intuition, and some of my experiment supports my guess. However, I did see the opposite behavior in another environment. Can someone shed me some light on this? Any help is appreciated, thanks.

    Read the article

  • Beware of const members

    - by nmarun
    I happened to learn a new thing about const today and how one needs to be careful with its usage. Let’s say I have a third-party assembly ‘ConstVsReadonlyLib’ with a class named ConstSideEffect.cs: 1: public class ConstSideEffect 2: { 3: public static readonly int StartValue = 10; 4: public const int EndValue = 20; 5: } In my project, I reference the above assembly as follows: 1: static void Main(string[] args) 2: { 3: for (int i = ConstSideEffect.StartValue; i < ConstSideEffect.EndValue; i++) 4: { 5: Console.WriteLine(i); 6: } 7: Console.ReadLine(); 8: } You’ll see values 10 through 19 as expected. Now, let’s say I receive a new version of the ConstVsReadonlyLib. 1: public class ConstSideEffect 2: { 3: public static readonly int StartValue = 5; 4: public const int EndValue = 30; 5: } If I just drop this new assembly in the bin folder and run the application, without rebuilding my console application, my thinking was that the output would be from 5 to 29. Of course I was wrong… if not you’d not be reading this blog. The actual output is from 5 through 19. The reason is due to the behavior of const and readonly members. To begin with, const is the compile-time constant and readonly is a runtime constant. Next, when you compile the code, a compile-time constant member is replaced with the value of the constant in the code. But, the IL generated when you reference a read-only constant, references the readonly variable, not its value. So, the IL version of the Main method, after compilation actually looks something like: 1: static void Main(string[] args) 2: { 3: for (int i = ConstSideEffect.StartValue; i < 20; i++) 4: { 5: Console.WriteLine(i); 6: } 7: Console.ReadLine(); 8: } I’m no expert with this IL thingi, but when I look at the disassembled code of the exe file (using IL Disassembler), I see the following: I see our readonly member still being referenced by the variable name (ConstVsReadonlyLib.ConstSideEffect::StartValue) in line 0001. Then there’s the Console.WriteLine in line 000b and finally, see the value of 20 in line 0017. This, I’m pretty sure is our const member being replaced by its value which marks the upper bound of the ‘for’ loop. Now you know why the output was from 5 through 19. This definitely is a side-effect of having const members and one needs to be aware of it. While we’re here, I’d like to add a few other points about const and readonly members: const is slightly faster, but is less flexible readonly cannot be declared within a method scope const can be used only on primitive types (numbers and strings) Just wanted to share this before going to bed!

    Read the article

  • Breaking through the class sealing

    - by Jason Crease
    Do you understand 'sealing' in C#?  Somewhat?  Anyway, here's the lowdown. I've done this article from a C# perspective, but I've occasionally referenced .NET when appropriate. What is sealing a class? By sealing a class in C#, you ensure that you ensure that no class can be derived from that class.  You do this by simply adding the word 'sealed' to a class definition: public sealed class Dog {} Now writing something like " public sealed class Hamster: Dog {} " you'll get a compile error like this: 'Hamster: cannot derive from sealed type 'Dog' If you look in an IL disassembler, you'll see a definition like this: .class public auto ansi sealed beforefieldinit Dog extends [mscorlib]System.Object Note the addition of the word 'sealed'. What about sealing methods? You can also seal overriding methods.  By adding the word 'sealed', you ensure that the method cannot be overridden in a derived class.  Consider the following code: public class Dog : Mammal { public sealed override void Go() { } } public class Mammal { public virtual void Go() { } } In this code, the method 'Go' in Dog is sealed.  It cannot be overridden in a subclass.  Writing this would cause a compile error: public class Dachshund : Dog { public override void Go() { } } However, we can 'new' a method with the same name.  This is essentially a new method; distinct from the 'Go' in the subclass: public class Terrier : Dog { public new void Go() { } } Sealing properties? You can also seal seal properties.  You add 'sealed' to the property definition, like so: public sealed override string Name {     get { return m_Name; }     set { m_Name = value; } } In C#, you can only seal a property, not the underlying setters/getters.  This is because C# offers no override syntax for setters or getters.  However, in underlying IL you seal the setter and getter methods individually - a property is just metadata. Why bother sealing? There are a few traditional reasons to seal: Invariance. Other people may want to derive from your class, even though your implementation may make successful derivation near-impossible.  There may be twisted, hacky logic that could never be second-guessed by another developer.  By sealing your class, you're protecting them from wasting their time.  The CLR team has sealed most of the framework classes, and I assume they did this for this reason. Security.  By deriving from your type, an attacker may gain access to functionality that enables him to hack your system.  I consider this a very weak security precaution. Speed.  If a class is sealed, then .NET doesn't need to consult the virtual-function-call table to find the actual type, since it knows that no derived type can exist.  Therefore, it could emit a 'call' instead of 'callvirt' or at least optimise the machine code, thus producing a performance benefit.  But I've done trials, and have been unable to demonstrate this If you have an example, please share! All in all, I'm not convinced that sealing is interesting or important.  Anyway, moving-on... What is automatically sealed? Value types and structs.  If they were not always sealed, all sorts of things would go wrong.  For instance, structs are laid-out inline within a class.  But what if you assigned a substruct to a struct field of that class?  There may be too many fields to fit. Static classes.  Static classes exist in C# but not .NET.  The C# compiler compiles a static class into an 'abstract sealed' class.  So static classes are already sealed in C#. Enumerations.  The CLR does not track the types of enumerations - it treats them as simple value types.  Hence, polymorphism would not work. What cannot be sealed? Interfaces.  Interfaces exist to be implemented, so sealing to prevent implementation is dumb.  But what if you could prevent interfaces from being extended (i.e. ban declarations like "public interface IMyInterface : ISealedInterface")?  There is no good reason to seal an interface like this.  Sealing finalizes behaviour, but interfaces have no intrinsic behaviour to finalize Abstract classes.  In IL you can create an abstract sealed class.  But C# syntax for this already exists - declaring a class as a 'static', so it forces you to declare it as such. Non-override methods.  If a method isn't declared as override it cannot be overridden, so sealing would make no difference.  Note this is stated from a C# perspective - the words are opposite in IL.  In IL, you have four choices in total: no declaration (which actually seals the method), 'virtual' (called 'override' in C#), 'sealed virtual' ('sealed override' in C#) and 'newslot virtual' ('new virtual' or 'virtual' in C#, depending on whether the method already exists in a base class). Methods that implement interface methods.  Methods that implement an interface method must be virtual, so cannot be sealed. Fields.  A field cannot be overridden, only hidden (using the 'new' keyword in C#), so sealing would make no sense.

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >