Having an inherited function return the derived type instead of the base type

I am writing two classes in C#:
A Matrix class
that represents a general Matrix with n-by-m dimensions
A SquareMatrix class
that inherits from Matrix and
has the constraint of being n-by-n
The reason I designed it this way is because square matrices support additional specific operations like calculating the determinant or the inverse, so being able to guarantee that those functions are avaliable with the specific type you're using are nice things
to have. Additionally it would support all the regular Matrix operations and can be used as a Matrix
I have a function in Matrix called getTranspose().
It calculates the transpose of the Matrix and returns it as a new Matrix
I inherited it in SquareMatrix,
but because the transpose of a square matrix is guaranteed to be square matrix, I also want it to return a SquareMatrix
I am unsure about the best way to do this.
I can re-implement the function in SquareMatrix,
but that would be code duplication because it's essentially the same calculation
I can use implicit typecast operators, but if I understand correctly that would cause unnecessary allocations (upcast SquareMatrix to Matrix,
create a new Matrix as
the transpose, create a new SquareMatrix during
typecasting and throw away the tranposed Matrix)
I can use explicit typecast operators, but it would be stupid to have to typecast the transpose of a SquareMatrix explicitly,
and it also has the same problem of the implicit operator with unnecessary allocations
Is there another option? Should I change the design of having SquareMatrix inherit
from Matrix?
This problem also applies to operators. It seems that I have to either implement typecasting operators which might cost in performance, or have to re-implement the same code.

Inheritance not helping to eliminate repetition and typecasts is often a sign that generics would help. You can do something like:
public T getTranspose<T>()
// or non-member function
T getTranspose<T>(T input)
I haven't fully worked it out, but it seems it might get awkward on the calling side. I know C# does some inference with generic methods, but I don't know C#, so I'm not familiar with the details. That might be the way you have to go, though, if you want
full compile-time type checking with the least amount of repetition in the implementation.
Another option would be to create private helper functions, then pass in the result type you want, for the helper to populate, like:
public SquareMatrix getTranspose() {
SquareMatrix result = new SquareMatrix();
transposeHelper(result);
return result;
This gives you more boilerplate on the implementation side, but at least it isn't full repetition.
A third option is just to check if the result is square in the Matrix implementation, and return a
SquareMatrix if it is, like:
public Matrix getTranspose() {
Matrix result;
if (resultIsSquare())
result = new SquareMatrix();
else
result = new Matrix();
// calculate result
return result;
This has the advantage of not needing any implementation at all for getTranspose() in
SquareMatrix, but at the expense of requiring type checking of the return value at the call site. It also works for cases like multiplying two non-square matrices that happen to give a square result. You give up most compile-time type checking,
though.
If your application happens to mostly require run-time instead of compile-time type checking anyway, you might as well just give up the different types and throw an exception if you call a method that a non-square matrix doesn't support. I believe this is
the approach most existing libraries take, especially since there are other conditions than being non-square that can cause methods like
inverse() to fail.
Speaking of libraries, there are a lot of good ones out there for matrix math, that are already heavily tested and optimized. Don't reinvent the wheel if you don't have to.

Similar Messages

  • First time going to a site where I do not have access and clicking the back button I'm returned to the root site instead of the site I started from

    Greetings,
    I have SharePoint 2013 enterprise using ADFS for authentication.  I have an issue where the first time going to a site where you do not have access and clicking the back button you're returned to the root site instead of the site you
    started from.
    ie:
    1) at site http://www.sharepoint.com/sites/finance/home.aspx
    2) browse to
    http://www.sharepoint.com/sites/finance/private/home.aspx
    3) receive a message: you do not have access to this site  ((oops went to the wrong location - I'll hit the back button))
    4) click the browser back button
    5) get returned to http://www.sharepoint.com/pages/home.aspx
    This only happens the first time browsing to a site that I do not have rights to, after this I can browse to the same site and hit the browser back  button and return to the correct site, or any other site that I do not have access to.
    Any ideas as to why this happens?  Ideas of where to start looking?
    Thanks

    Hi Robert,
    From your description, when you receive access denied message and hit back button in browser, it redirects you to the root site but not previous site. However, this just happens at the first time.
    You may try to use some tool or check log which can tell us how does it handle the request when you hit the button. And compare the issue time and non-issue time.
    I'd suggest you use Netmon tool:
    http://blogs.msdn.com/b/carloshm/archive/2012/11/08/sharepoint-2013-network-monitor-parsers.aspx
    Regards,
    Rebecca Tu
    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
    [email protected]

  • How do i show the filename.type instead of the entire file path?

    How do i show the filename.type instead of the entire file path?
    I want it to show "ProgramSetup.exe" instead of "C:/Program Files/Oracle/JavaFX/ProgramSetup.exe"
    I have created a JavaFX program with the help of my manager
    below are the code
                   File file = fileChooser.showOpenDialog(Admin.mainStage);
                   if (file != null) {
                        textFiles.setText(file.getAbsolutePath());
                        String absolutePath = file.getAbsolutePath();
                        //String fileName = new File(absolutePath).getName();the reason i put the last line as // because it has error on that line....
    if i remove the last line, it will display but with the full path....
    i search through google and the guide on many forums aren't clear to me.....some said there are 2 ways but i tried and it is not working, atleast for me...maybe i left out something or what....can anyone help me on this?

    You don’t need the absolutePath:
    File file = fileChooser.showOpenDialog(Admin.mainStage);
                   if (file != null) {
                        textFiles.setText(file.getName());
                               }

  • My new iPad mini is connected to a Logitech keyboard but can't seem to get it to type instead of the touch screen version on the iPad - any hints?

    My new iPad mini is connected to a Logitech keyboard but can't seem to get it to type instead of the touch screen version on the iPad - any hints?
    Michael

    Is this a Bluetooth keyboard?
    Have you turned on Bluetooth in iPad's Settings app?

  • Application messages are in the system log instead of the application log

    Hi SAP GURUS.
    The standard output is created from the outbound delivery .
    All the messages are hitting the system log instead of the application log .
    This is after the upgrade from 4.6c to ECC 6.0 .
    Please provide the details how to move the log to the application log since the output is the standard output (SAP provided output type ).

    verzunof wrote:
    Hello,
    My system.log is filled with these messages, they repeat every second.
    Jan 21 18:31:47 Maki-Mac kernel[0]: AppleFWOHCI_AsyncReceive::waitForDMA - context not going inactive.
    Jan 21 18:31:47 Maki-Mac kernel[0]: AppleFWOHCI_AsyncTransmit::waitForDMA - context not going inactive.
    Do these messages indicate a problem? If so what that could be problem and the solution?
    Can this contribute to the sleep/wakeup problem when iMac won't wakeup after being put to sleep manually and not sleeping according to Power Saving settings?
    Thanks a lot.
    verzunof wrote:
    I'm not certain if those messages indicate a power issue but you can try *resetting the System Management Controller* and see if that helps. Here's how: http://support.apple.com/kb/HT1806
    "The System Management Controller (SMC) is a chip on the logic board that controls all power functions for your computer. If your computer is experiencing any power issue, resetting the SMC may resolve it. The SMC controls several functions, including:
    Telling the computer when to turn on, turn off, sleep, wake, idle, and so forth.
    Handling system resets from various commands.
    Controlling the fans."
    Carolyn

  • Populating the user group instead of the group ID in MFA

    Hello all,
    I am trying to Populate the user group instead of the group ID in MFA. I want to use this to create authorization permissions, after authentication. I am running into the problem of not getting any info after authentication in the attribute dump.  Are
    there settings that I can change in order to Populate the attribute dump? are there settings that I can change to get all of the groups that each user is in?
    Thanks,
    Levi Williams
    IT professonial
    Intern

    Hi Levi Williams,
    Thanks for posting here!
    Refer to the solution in this  thread link:
    https://social.msdn.microsoft.com/Forums/en-US/df060757-8190-4083-a162-0876cd4b8d15/group-based-radius-return-attributes?forum=windowsazureactiveauthentication
    Additional reference:
    http://www.rdsgurus.com/uncategorized/step-by-step-using-windows-server-2012-r2-rd-gateway-with-azure-multifactor-authentication/
    Hope this helps!
    Regards,
    Sadiqh

  • What's wrong with the built-in keyboard on my macbook? The caps button does not work rite, no matter what letter button i push they all come out capitals and the number keys when pushed display the special characters instead of the numbers!

    the built-in keyboard on my macbook is not functioning right, the number keys when pushed display the special characters instead of the numbers,
    the caps button doesn't work at all, the letter buttons display capitals when pushed whether the caps button is on or off, the shift keys are also out of whack!!
    It seems it somehow got relocated to the "0" button because if you push and hold the zero button down the keyboard seems to operate normally, the number keys display numbers when pushed the letter keys display lower case when pushed but release the zero button and your back in the twilight zone!! Can anybody help me resolve this issue? one more thing im using an external usb keyboard right now and it seems to function properly if that helps any.

    You would do better in the actual macbook pro forums (this is not).

  • When i link a page to send my email the page comes up in the adress box instead of the subject box

    when i right click a page to e-mail the link to the page appears in the address bar instead of the body of the e-mail

    Mark,
    I understand that you are frustrated with a changed functionality of an email website that you use. There is a feature in Firefox that switches to a tab immediately in the "3bar" menu > Options under Tabs, please make sure that nothing has changed.
    Please also update to version 32, and post back with your results.

  • Why does my text in Indesign start on the right side instead of the left?

    I have done something to the newsletter that I am working on, but I don't know what I did.
    Whenever I try to write a caption on a picture or try to type a piece of text for the newsletter, the cursor starts on the right side instead of the left and makes weird spacing and never lines up correctly.
    The only way I can get text to work now is to use a snipping tool and snip text from another program!

    With just the text tool selected, but no text boxes selected (or made), any change to the style of paragraphs or fonts etc is 'set' for the document. If you have clicked on the right alignment tool with nothing selected, then everything from then onwards will default to right align.
    If every document you've worked on is doing this, then open InDesign with no document open (so just the panels showing, but no file/doc open) and select left align with the text tool in use. Any setting made with InDesign like this, is default for any new document created. Colours, alignment, optical kerning, fonts, sizes, leading etc etc changed in this state, is the new default.

  • Send email to the Form Submitter instead of the process creator

    Hi,
    Can any one please show me how to make a process to send an email notification to the Form Submitter instead of the Process Creator.
    Here is my brief desc on my process: Form Filler (can be anyone) send the filled form for a list of employees to the one who request (the 1st employee name on the list of the form) then this he/she then submit the form (form submitter) to process to route it to the manager. Whether the mgr is approved or denied then the process is completed by sending to his/her for status of that request. I was able to have it to send the email to the process creator (creator_id) but not the Form Sumitter. Can any one please help.
    Thanks,
    Han Dao

    Hi Han
    I guess I should have double checked the version with you first!
    If I remember correctly, in 8.2.1 there are a few more steps involved.
    On the Assign Task service...Form Data Mapping tab, is a field called "Completed user id".
    This is:
    The location to store the GUID (Global Unique Identifier) representing the user who completed the task. The data type is string.
    You need to create a string variable to hold that value.
    You select that in the "Completed user id" field.
    Because this is a GUID, you will then have to do a User Lookup (under Foundation) to find your user.
    (http://livedocs.adobe.com/livecycle/8.2/wb_help/wwhelp/wwhimpl/js/html/wwhelp.htm)
    You can then use those results in the To field of the SendWithDocument.
    Hope this helps.
    Diana

  • TS3623 purchasing a movie from apple tv has stopped working.  I click on "movies" and it takes me back to the same screen instead of the movies available.  I have updated software, unplugged the modem & apple tv box, & the tv; Netflix still works!

    purchasing a movie from apple tv has stopped working.  I click on "movies" and it takes me back to the same screen instead of the movies available.  I have updated software, unplugged the modem & apple tv box, & the tv; Netflix still works!

    Welcome to the Apple Community.
    First you should try logging out of your iTunes Store account (settings > iTunes Store > accounts) and then back in again.
    If that doesn't help, try resetting the Apple TV (Settings > General > Reset > Reset all settings). You should also try restarting your router.
    If both of the above don't help, you should try a restore (Settings > General > Reset > Restore).

  • In Windows 8, how can I see an image of the psd file instead of the Photoshop icon?

    In Windows 8, how can I see an image of the psd file instead of the Photoshop icon?

    There are a number of third party solutions for this.  I just use Bridge, so can't recommend one in particular.

  • HT1657 I rented a movie and was charged for it, it started to download but says I do not have enough space.  I tried to delete it so I could download the SD version instead of the HD version but am unable to do that  what can I do???

    I rented a movie and was charged for it, it started to download but says I do not have enough space.  I tried to delete it so I could download the SD version instead of the HD version but am unable to do that  what can I do???

    Same thing happened to me ipad. Please someone fix it Apple.

  • Using the file icon instead of the Thumbnail icon

    is it possible to use the file icon instead of the thumbnail icon on the desktop? If so, how?
    Thanks,
    Travis

    View menu --> Show view options --> Show Icon preview --> uncheck it

  • Wenn I've made changes on my private home-page and want to see the result, how do I get my Mac to load the new side instead of the "old" one?

    When I've worked on my private home-page and want to controll the results, how do I get my Mac to take the new version instead of the old one? I tried cmd R without any change! Who knows? Nina

    Try clearing the cache - command-option-e in Safari.

Maybe you are looking for

  • Folder containing Swedish characters isn't recognise. IsDirectory()

    Hello! I have a problem with an application that is supposed to delete folders containing to files. It works fine but a folders name contain Swedish charters the applications doesn't work because that folder doesn't get recognizes as a directory by i

  • Language Selection Option - Pages 5.

    Hello!    I am not to convinced about the Language Selection Options on new Pages 5. I do translations and work with different laguages simultaneously. With Pages '09 I had no problem with language. Pages 5 does not automatically detects language, ho

  • Submit Function Pool

    Hi, I have a requirement, to call the standard transaction skiping the initial screen ( passing the selection screen values to initial screen ) thru program ( SE38 ). So if i applied for Call Transaction, there is no parameter ID for the input of str

  • Problem with Syncing 48000 hz Camera audio with 44100 hz lapel audio? Need help any suggestions?

    I recently did a project and recorded my video with 48000 hz and then on accidentally recorded my lapel mic audio with 44100 hz. I now need to sync the two together but seems impossible? What should I do? I have tried to convert the audio in audacity

  • How to restart(--replace) gnome-shell Ctrl+Alt+F*

    Hi, I'm having random Gnome-shell freezes, everything seems to be working fine except for the shell itself, which seems to be completely frozen. I want to restart it using CTRL+ALT+F* and gnome-shell --replace or mutter--replace , but I get this: Win