c# - How to write a method/new constructor for an existing class/structure? Padding(int Horizontal, int Vertical) -


i'm trying learn c# building windows form , i've run across haven't been able find answer searching. search results may have provided me answer (that it's not possible), wanted confirm before giving up.

i'm creating form has multiple panels and/or flowlayoutpanels, each multiple controls. i'm attempting dynamically calculate amount of space controls take can add padding panel/flowlayoutpanel center controls. there may better ways of doing using anchors, i'm learning , best way think of tackle specific problem me learn.

as i've worked through problem, i've realized padding structure doesn't have constructor make things easier on me i've seen in other apps (specifically microsoft office & vba). want able create new padding() has constructor accepts (int horizontal, int vertical) or (int horizontal) or (int vertical) 'horizontal' int copied .left , .right properties of control, , 'vertical' int copied .top , .bottom properties of control.

so, question: is there way write constructor existing class/structure or way overload padding structure allow me obtain padding want 2 values instead of four?

thanks...

you can derive new class existing class, provided existing class not sealed. in case class struct, , cannot derive struct.

through extension methods can add instance-like methods existing classes, can't add static methods or constructors existing classes.

when i'm in such situation, create new static utility class want. example:

public static class paddingutil {     public static padding fromhv(int horizontal, int vertical)     {         return new padding(horizontal, vertical, horizontal, vertical);     } } 

and use this:

padding p = paddingutil.fromhv(10, 20); 

your questions indicate don't understand basics of c#. suggest book c# , read it.

but out now:

  • to assign value field or property of object, this:

    padding p = paddingutil.fromhv(10, 20); mycontrol.padding = p; 

    or equivalently:

    mycontrol.padding = paddingutil.fromhv(10, 20); 
  • to current value of field or property of object, this:

    padding p = mycontrol.padding; 
  • to change properties on padding struct:

    padding oldpadding = mycontrol.padding; padding newpadding = new padding(     10, // left     oldpadding.top,     10, // right     oldpadding.bottom); mycontrol.padding = newpadding; 

you can turn last example extension method. google it, or search stack overflow.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -