Reputation: 701
This is my function to move the scrollbars (I have horizontal one and a vertical one)
private void moveTheScroll(object sbar, int scrollDiff)
{
if (sbar is HScrollBar)
{
int newScrollvalue = ((HScrollBar)sbar).Value + scrollDiff;
if (((HScrollBar)sbar).Minimum < newScrollvalue &&
newScrollvalue < ((HScrollBar)sbar).Maximum)
((HScrollBar)sbar).Value = newScrollvalue;
}
else if (sbar is VScrollBar)
{
int newScrollvalue = ((VScrollBar)sbar).Value + scrollDiff;
if (((VScrollBar)sbar).Minimum < newScrollvalue &&
newScrollvalue < ((VScrollBar)sbar).Maximum)
((VScrollBar)sbar).Value = scrollDiff;
}
}
Is there a way to to not typecast the object every single time I want to use it and make an alias instead? Something similar to this (this doesnt work because v cannot be initialized)
var v;
if(sbar is HScrollBar)
v = (HScrollBar)sbar;
else if(sbar is VScrollBar)
v = (VScrollBar)sbar;
v.Value = newValue;
Upvotes: 1
Views: 63
Reputation: 101731
If both types are inheriting from Scrollbar
class then you just need to perform one cast:
private void moveTheScroll(object sbar, int scrollDiff)
{
var scrollBar = sbar as ScrollBar;
if(scrollBar != null)
{
int newScrollvalue = scrollBar.Value + scrollDiff;
// do other works with scrollBar...
}
}
Upvotes: 1